码迷,mamicode.com
首页 > 其他好文 > 详细

Core Data 数据操作 增删改查

时间:2015-08-13 01:12:08      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:

所有操作都基于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];
}

 

Core Data 数据操作 增删改查

标签:

原文地址:http://www.cnblogs.com/fortunely/p/4725982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!