Core Data 基本数据操作 增删改查 排序
所有操作都基于Core Data框架相关 API,工程需要添加CoreData.framework支持
1.增 NSEntityDescription insertNewObjectForEntityForName: inManagedObjectContext:
利用NSEntityDescription工厂方法创建Entity
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; //get NSManagedObjectContext NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSManagedObject *managedObject = nil; managedObject = [NSEntityDescription insertNewObjectForEntityForName:youEntityName inManagedObjectContext:context];//youEntityName is a NSString [managedObject setValue:youKeyValue forKey: youEntityKeyName];//KVO方式赋值value - key //e.g. [managedObject setValue:[name descrition] forKey: @"kEntityKeyName"], the entity must include name property, and its name must be "kEntityKeyName" [appDelegate saveContext];//Don't forget to save the changes
2.删 context deleteObject:
NSManagedObject * deleteObject = youWillDeleteObject;//Can get the object from the query result , which is a NSArray getting by the way of using NSFetchRequest /*e.g. NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntityName]; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; //choose one object or many objects */ AppDelegate *delegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [delegate managedObjectContext]; [context deleteObject:deleteObject];//从NSManagedObjectContext中删除指定对象 [delegate saveContext];//保存修改
3.改 略
4.查
4.1查找全部context executeFetchRequest: error:
NSMutableArray *_array;//声明存储数据的数组 AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntityName]; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; if (objects == nil) { NSLog(@"There is an error!"); }else{ _array = [NSMutableArray arrayWithArray:objects]; }
5.排序[NSSortDescriptor sortDescriptorWithKey:], [request setSortDescriptors:]
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:kEntityName];//查找请求 //创建排序描述器 : 按创建时间属性列(Entity设计时添加此列@"createTime"(date类型))进行增序排序 NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:kCreateTime ascending:YES]; //设置查找请求的排序描述器 [request setSortDescriptors:[NSArray arrayWithObject:sort]]; //利用Coredata api在数据库中查 NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error];