所有操作都基于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]; [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]; }
时间: 2024-10-07 09:22:00