iOS CoreData 使用

  • 手动创建 xcdatamodeld 文件


    创建xcdatamodeld 文件

    DB.xcdatamodeld
  • 创建相关数据类型


    屏幕快照 2019-03-01 上午9.38.08.png

    屏幕快照 2019-03-01 上午9.38.38.png
  • 然后生成如下几个文件


    屏幕快照 2019-03-01 上午9.39.00.png
  • 导入 #import "UserInfo+CoreDataClass.h" 即可

  • 创建表文件

// 创建表
-(void)createTable
{
    // 在沙盒Library/Caches 中创建
    NSString *cacheDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath = [NSString stringWithFormat:@"%@/UserInfo.sqlite",cacheDirectory];
    NSURL *pathUrl = [[NSBundle mainBundle] URLForResource:@"DB" withExtension:@"momd"];
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:pathUrl];
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

    NSLog(@"dbPath - %@",dbPath);
    NSError *error = nil;
    NSURL *url = [NSURL fileURLWithPath:dbPath];
    [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:NULL URL:url options:NULL error:&error];
    if (error == nil) {
        NSLog(@"数据库添加成功");
    } else {
        NSLog(@"数据库添加失败");
    }
    NSLog(@"%@",error);
    _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    _context.persistentStoreCoordinator = psc;
}
  • 添加数据
// 添加数据
-(void)addUserInfo
{
    UserInfo *user = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo" inManagedObjectContext:_context];
    user.name = @"Roy";
    user.age = 18;
    user.sex = @"男";
    
    NSError *saveError = nil;
    BOOL result = [_context save:&saveError];
    result == YES ? NSLog(@"添加成功") : NSLog(@"添加失败");
}
  • 删除数据
// 删除数据
-(void)deleteUserInfo
{

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"UserInfo"];
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"age>=6"];
    fetchRequest.predicate = pre;
    
    NSError *error = nil;
    NSArray *arrResult = [_context executeFetchRequest:fetchRequest error:&error];
    if (arrResult.count > 0) {
        for (UserInfo *user in arrResult) {
            NSLog(@"age - %lld",user.age);
            [_context deleteObject:user];
        }
        BOOL result = [_context save:NULL];
        result == YES ? NSLog(@"删除成功") : NSLog(@"删除失败");
    }
}
  • 修改数据
// 修改数据
-(void)changeUser
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"UserInfo"];
    NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"age=%d",18];
    fetchRequest.predicate = predicate;
    NSError *error = nil;
    NSArray *arrResult  = [_context executeFetchRequest:fetchRequest error:&error];
    for (UserInfo *user in arrResult) {
        NSLog(@"%lld",user.age);
        user.age = 20;
    }
    BOOL result = [self.context save:&error];
    result == YES? NSLog(@"修改成功"):NSLog(@"修改失败");
}
  • 查询数据
// 查询数据
-(void)queryUserInfo
{
    //获取这个类
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserInfo" inManagedObjectContext:_context];
    //创建查询请求
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    //设置查询请求的实体
    [fetchRequest setEntity:entity];
    NSArray *arrResult = [self.context executeFetchRequest:fetchRequest error:nil];
    for (UserInfo *user in arrResult) {
        NSLog(@"名字是:%@ 性别是:%@ 年龄是:%lld",user.name,user.sex,user.age);
    }
}

你可能感兴趣的:(iOS CoreData 使用)