CoreData增删改查

  • 创建模型
CoreData增删改查_第1张图片
自动生成模型.png
  • 创建数据库
#pragma mark - 创建数据库
///创建数据库
-(void)createCoreDataBase{
    //1 NSManagedObjectModel , xcdatamodeld文件编译打包到bundle中,转变成momd文件
    NSURL *dataUrl = [[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];
    NSManagedObjectModel *dataModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:dataUrl];
    
    //2 根据dataModel对象创建协调器
    // 1>创建协调器 (建立数据<--->MO对象的联系)
    // 使用这个对象,间接操作数据库文件
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:dataModel];
    
    //2>给协调器对象添加一个持久化的对象
    //数据库文件在沙盒保存的路径
    NSString *persistentPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/PersistentStore.sqlite"];
    
    NSURL *persistentUrl = [NSURL fileURLWithPath:persistentPath];
    
    NSError *addError = nil;
    
    /*CoreData支持的存储数据的文件类型
     NSSQLiteStoreType:SQLite
     NSXMLStoreType    XML
     NSBinaryStoreType 二进制
     NSInMemoryStoreType 只保存在内存中
     */
    [psc addPersistentStoreWithType:NSSQLiteStoreType
                      configuration:nil //配置
                                URL:persistentUrl //数据库文件保存的路径
                            options:nil error:&addError];
    
    //指定contex使用哪个协调器写入数据库
    self.context.persistentStoreCoordinator = psc;

  • 增加数据
///添加数据
-(void)addObject{
    
    Student *student1 = [NSEntityDescription insertNewObjectForEntityForName:@"Student"
                                             inManagedObjectContext:self.context];
    student1.sId = 001;
    student1.name = @"猪八戒";
    student1.number = 1234;
    student1.classes = @"软件1303";
    
    //2 把上下文的变化保存下来
    NSError *saveError = nil;
    [self.context save:&saveError];
}

  • 删除数据
/// 删除数据
-(void)deleteObjects{
    
    //(1)抓取请求
    NSFetchRequest *fetchR = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number>%f",10.0];
    fetchR.predicate = predicate;
    
    //(2)执行请求
    NSArray *students = [self.context executeFetchRequest:fetchR error:nil];
    
    for (Student *s in students) {
        
        //删除
        [self.context deleteObject:s];
    }
    
    //(3)保存
    [self.context save:NULL];
    
    
}

  • 修改数据
/// 更新数据
-(void)updateObject{
    
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //(1) 指定查询的实体
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.context];
    [fetchRequest setEntity:entity];
    
    //(2)查询的条件
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number>%f", 100.0];
    [fetchRequest setPredicate:predicate];
    
    //(3)排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"number"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    //(4)执行
    NSError *error = nil;
    NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
    
    for (Student *s in fetchedObjects) {
        
        s.name = @"沙僧";
        s.age = 10;
    }
    
    //(5)保存
    [self.context save:NULL];
}

  • 查询数据
/// 查询数据
-(void)queryObjects{
    
    //1 抓取请求
    NSFetchRequest *fetchedRequest = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    //(1)查询的条件 (谓词)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number>%f",1.0];
    fetchedRequest.predicate = predicate;
    
    //(2)排序
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES];//升序
    NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];//升序
    fetchedRequest.sortDescriptors = @[sort1,sort2];
    
    //(3)限制查询的条数
    //    fetchedRequest.fetchLimit = 20;
    
    //(4)从第几天数据开始返回
    //    fetchedRequest.fetchOffset = 3; //
    
    //2 执行查询的请求
    NSArray *result = [self.context executeFetchRequest:fetchedRequest error:nil];
    
    for (Student *s in result) {
        
        NSLog(@"number = %lld name = %@",s.number,s.name);
        
    }
}

你可能感兴趣的:(CoreData增删改查)