iOS coredata增、删、改、查

  • 1.增(插入)
AppDelegate *appDelegate = [AppDelegate delegate];
 NSManagedObjectContext *context = [appDelegate managedObjectContext];
//读取这个类(分号里面是表名)
SecretaryTaoSQL *theObject = [NSEntityDescription insertNewObjectForEntityForName:@"SecretaryTaoSQL" inManagedObjectContext:context];
theObject.xxID =  dic[@"id_"];
theObject.orgID = dic[@"org_id_"];
theObject.createTime = dic[@"create_time_"];
theObject.ywID = dic[@"yw_id_"];
theObject.ywType = dic[@"yw_type_"];
theObject.msgContent = dic[@"msg_content_"];
theObject.status = [dic[@"status_"] description];
theObject.taoType = @"1"
[context save:nil];
  • 2.删
AppDelegate *appDelegate = [AppDelegate delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//读取这个类
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"SecretaryTaoSQL" inManagedObjectContext:context];
//建立请求
 NSFetchRequest *request = [[NSFetchRequest alloc]init];
 [request setIncludesPropertyValues:NO];
//建立请求的是哪一个类
 [request setEntity:entityDescription];
NSError *error = nil;
 NSArray *datas = [context executeFetchRequest:request error:&error];
if (!error && datas && [datas count])
 {
        for (NSManagedObject *obj in datas)
        {
            [context deleteObject:obj];
            [context save:nil];
        }
        if (![context save:&error])
        {
            NSLog(@"error:%@",error);
        }
  }
  • 3.查
AppDelegate *appDelegate = [AppDelegate delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//读取这个类
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"SecretaryTaoSQL" inManagedObjectContext:context];
//建立请求
NSFetchRequest *request = [[NSFetchRequest alloc]init];
//建立请求的是哪一个类
[request setEntity:entityDescription];
//获取所有的信息放到数组里面
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
//objects即所查数据
  • 4.改
AppDelegate *appDelegate = [AppDelegate delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//读取这个类
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"SecretaryTaoSQL" inManagedObjectContext:context];
//建立请求
 NSFetchRequest *request = [[NSFetchRequest alloc]init];
 [request setIncludesPropertyValues:NO];
//建立请求的是哪一个类
 [request setEntity:entityDescription];
request.predicate = [NSPredicate predicateWithFormat:@"orgID = %@",orgID];
NSError *error = nil;
 NSArray *datas = [context executeFetchRequest:request error:&error];
 for (SecretaryTaoSQL *info in datas) {
        info.ywType = @"2";
    }
    
    //保存
    if ([context save:&error]) {
        //更新成功
        NSLog(@"更新成功");
    }

欢迎来交流 qq:245852750

你可能感兴趣的:(iOS coredata增、删、改、查)