作为管理器,最基本的功能就是增删改查了。
1、插入
AppDelegate *app = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [app managedObjectContext]; NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"entityname" inManagedObjectContext:context]; [newManagedObject setValue:value forKey:@"propertyname"]; NSError *error; if (![context save:&error]) { // Handle the error… }
2、查询
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Hero" inManagedObjectContext:managedObjectContext]; NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc]initWithKey:@”name” ascending:YES]; NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc]initWithKey:@”secretIdentity” ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor1, sortDescriptor2, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; [fetchRequest setEntity:entity]; [fetchRequest setFetchBatchSize:20]; NSArray *objecs = [context executeFetchRequest: fetchRequest error:&error]; if(objets==nil || error != nil){ //做处理 }
3、修改
-(void)applicationWillResignActive:(NSNotification *)notification{ NSLog(@"applicationWillResignActive"); //创建托管对象上下文 NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc]init]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context]; [request setEntity:entityDescription]; NSManagedObject *user = nil; NSError *error; NSArray *objets = [context executeFetchRequest:request error:&error]; if(objets==nil){ NSLog(@"There has a error!"); //做错误处理 } if([objets count]>0){ //非第一次,更新数据 NSLog(@"更新操作"); user = [objets objectAtIndex:0]; }else{ NSLog(@"插入操作"); //第一次保存,插入新数据 user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context]; } [user setValue:self.serverIp.text forKeyPath:@"serverIp"]; [user setValue:self.userName.text forKeyPath:@"userName"]; [context save:&error]; }
4、删除
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; [context deleteObject:[objecs objectIndex:index]; NSError *error; if (![context save:&error]) { NSLog(@”Unresolved error %@, %@”, error, [error userInfo]); exit(-1); // Fail }
5、数据迁移
当程序变化时,在很多简单的情况下,Coredata提供了轻量级的自动数据迁移,比如以下三个情况可以通过开启CoreData自动迁移实现:
1.简单的增加一个字段
2.把一个必填字段改为可选字段
3.把可选字段改为必填字段(但一定要定义默认值)
时间: 2024-10-08 06:22:53