CoreData的基本使用

包括:

  • CoreData的初始化(非最新coredata)
  • CoreData的数据操作
  • 同一个数据库内表的关联
  • 多个数据库简单使用
1,CoreData的初始化(非最新coredata)
  • 1.1,创建数据库模型Data Model
Snip20170104_1.png
  • 1.2,创建NSManagedObject
Snip20170104_2.png
  • 1.3, 代码进行初始化
    //1,创建模型,并与文件进行关联,如果只有一个数据库,可以字节用nil表示
    //方式一:在只有一个数据库的时候
//    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    //方式二:在有多个数据库的时候会有多个数据库文件夹,所以需要指定特定的数据库文件夹,momd是默认数据库文件夹后缀名,如Company.momd
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"Company" withExtension:@"momd"];
    NSManagedObjectModel   *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
    
    //2,创建调度器,并设置存储路径
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Company.sqlite"];
    NSURL *url01 = [NSURL fileURLWithPath:path];//指定存储的文件名
    NSError *error;
    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url01 options:nil error:&error];
    
    //3, 创建上下文,并于调度器进行关联
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    context.persistentStoreCoordinator = coordinator;
2,CoreData的数据操作
  • 2.1, 增加数据
  • 多次数据添加只需要一次save即可
    //1.1, 增加数据
    Employee *employee01 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
    employee01.name = [NSString stringWithFormat:@"Jake"];
    employee01.height = @(1.59 + arc4random_uniform(6)*0.1);
    employee01.age = @(26+arc4random_uniform(4));
    
    Employee *employee02 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
    employee02.name = [NSString stringWithFormat:@"Mike"];
    employee02.height = @(1.59 + arc4random_uniform(6)*0.1);
    employee02.age = @(26+arc4random_uniform(4));
    
    NSError *errror;
    [self.context save:&errror];
    if (errror) {
        NSLog(@"%@",errror);
    }
    
    /*
     for (int i=0; i<100; i++) {
     Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
     employee.name = [NSString stringWithFormat:@"Jake"];
     employee.height = @(1.59 + arc4random_uniform(6)*0.1);
     employee.age = @(26+arc4random_uniform(4));
     
     Employee *employee01 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
     employee01.name = [NSString stringWithFormat:@"Mike"];
     employee01.height = @(1.59 + arc4random_uniform(6)*0.1);
     employee01.age = @(26+arc4random_uniform(4));
     
     NSError *errror;
     [self.context save:&errror];
     if (errror) {
     NSLog(@"%@",errror);
     }
     }
     */
  • 2.2, 查询数据
  • (因为删除和更新都是在查询的基础上做的,所以这里先进行查询操作)
//1, 创建请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    request.predicate = [NSPredicate predicateWithFormat:@"age < 28"];
    NSSortDescriptor *sort01 = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
    request.sortDescriptors = @[sort01];
    
    //2, 执行请求,返回数据
    NSError *error;
    NSArray *array = [self.context executeFetchRequest:request error:&error];
    //        NSLog(@"%@", array);
    
    //3, 解析数据
    [array enumerateObjectsUsingBlock:^(Employee *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSLog(@"%@---%@---%@",obj.name, obj.height, obj.age);
        
    }];
    
    /*
     //查找相关
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@", @"jack--1"];
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"4444"];
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@", @"zhang"];
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE %@", @"zha*"];
     
     //排序和数量显示
     NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
     fetchRequest.sortDescriptors = @[heightSort];
     fetchRequest.fetchOffset = 5*i;
     fetchRequest.fetchLimit = 5;
     */
  • 2.3, 删除数据
  • 注意在删除数据后需要重新保存一下才会真正的在数据库中删除
    //1, 创建请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", @"zhangzhang"];
    
    //2,执行请求
    NSError *errror;
    NSArray *array = [self.context executeFetchRequest:request error:&errror];
    
    //3,解析结果
    [array enumerateObjectsUsingBlock:^(Employee *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@---%@---%@", obj.name, obj.age, obj.height);
        [self.context deleteObject:obj];
        [self.context save:nil];
    }];
  • 2.4,更新数据
  • 更新完之后仍旧需要保存
 //1, 创建请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", @"Jake"];
    
    //2,执行请求
    NSError *errror;
    NSArray *array = [self.context executeFetchRequest:request error:&errror];
    
    //3,解析结果
    [array enumerateObjectsUsingBlock:^(Employee *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSLog(@"%@---%@---%@", obj.name, obj.age, obj.height);
        
        obj.name = @"zhangdanfeng";
        
        [self.context updatedObjects];
        [self.context save:nil];
        
    }];

3,同一个数据库内表的关联
  • 3.1, 创建其他表
Snip20170104_4.png
  • 3.2, 在coredata编辑页面进行关联
Snip20170104_5.png
  • 3.3, 关联好之后需要重新的创建模型(比如说之前的Employee模型代码文件里面是没有自动生成department信息的, 重新创建会自动生成,当然手写也可以)
Snip20170104_2.png
  • 3.4, 直接在代码中创建并赋值即可
  
    Department *department = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
    department.name = @"ios"; 
    
    Employee *employee01 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];
    employee01.name = [NSString stringWithFormat:@"zhangzhang"];
    employee01.height = @(1.59 + arc4random_uniform(6)*0.1);
    employee01.age = @(26+arc4random_uniform(4));
    //赋值
    employee01.department = department;
    
    NSError *errror;
    [self.context save:&errror];
    if (errror) {
        NSLog(@"%@",errror);
    }

4,多个数据库简单使用

  • 有多个数据库,初始化的时候必须要用方式二进行初始化
    //方式二:在有多个数据库的时候会有多个数据库文件夹,所以需要指定特定的数据库文件夹,momd是默认数据库文件夹后缀名,如Company.momd
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"Company" withExtension:@"momd"];
    NSManagedObjectModel   *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
  • 一个数据库对应一个上下文,如果有多个数据库,需要创建多个上下文,然后可以独立的进行每个数据库的操作,具体操作方法和上面的一样,只不过换一下上下文即可
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容