在看之前请先查看这篇内容点击打开链接 这里面对一些基本的操作已经很全面。我自己的学习也是总这么文章开始的。
先贴一个苹果官方的出事后一个coredata的方法
-
-(void)initializeCoreData
-
{
- //实例化数据模型
-
NSURL*modelURL=[[NSBundlemainBundle]URLForResource:@"DataModel"withExtension:@"momd"];
-
NSManagedObjectModel*mom=[[NSManagedObjectModelalloc]initWithContentsOfURL:modelURL];
-
NSAssert(mom!=nil,@"Error initializing Managed Object Model");
-
-
//实例化持久化存储调度器
-
NSPersistentStoreCoordinator*psc=[[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:mom];
-
NSManagedObjectContext*moc=[[NSManagedObjectContextalloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
- //指定上下文的调度器
-
[mocsetPersistentStoreCoordinator:psc];
-
[selfsetManagedObjectContext:moc];
-
//获取数据库路径和指定数据库名称
-
NSFileManager*fileManager=[NSFileManagerdefaultManager];
- //注意这儿需要的是文件路径
-
NSURL*documentsURL=[[fileManagerURLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask]lastObject];
-
NSURL*storeURL=[documentsURLURLByAppendingPathComponent:@"DataModel.sqlite"];
-
-
-
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^(void){
-
NSError*error=nil;
-
NSPersistentStoreCoordinator*psc=[[selfmanagedObjectContext]persistentStoreCoordinator];
-
//添加持久化存储 创建数据库
-
NSPersistentStore*store=[pscaddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURLoptions:optionserror:&error];
-
NSAssert(store!=nil,@"Error initializing PSC: %@\n%@",[errorlocalizedDescription],[erroruserInfo]);
-
});
-
}
如果我们有很多不同的模型,并且数据库文件也不确定 可以把上面的方法抽象成一个单例中得方法
-
-(void)initializeCoreDataWithModelName:(NSString *)modelName andDBName:(NSString *)dbName
-
{
- //实例化数据模型
-
NSURL*modelURL=[[NSBundlemainBundle]URLForResource:modelNamewithExtension:@"momd"];
-
NSManagedObjectModel*mom=[[NSManagedObjectModelalloc]initWithContentsOfURL:modelURL];
-
NSAssert(mom!=nil,@"Error initializing Managed Object Model");
-
-
//实例化持久化存储调度器
-
NSPersistentStoreCoordinator*psc=[[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:mom];
-
NSManagedObjectContext*moc=[[NSManagedObjectContextalloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
- //指定上下文的调度器
-
[mocsetPersistentStoreCoordinator:psc];
-
[selfsetManagedObjectContext:moc];
-
//获取数据库路径和指定数据库名称
-
NSFileManager*fileManager=[NSFileManagerdefaultManager];
- //注意这儿需要的是文件路径
-
NSURL*documentsURL=[[fileManagerURLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask]lastObject];
-
NSURL*storeURL=[documentsURLURLByAppendingPathComponent:dbName];
-
-
//这样做的目的 可能是为了快速返回上下文 减少启动时间 (个人猜想)
-
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^(void){
-
NSError*error=nil;
-
NSPersistentStoreCoordinator*psc=[[selfmanagedObjectContext]persistentStoreCoordinator];
-
//添加持久化存储 创建数据库
-
NSPersistentStore*store=[pscaddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURLoptions:optionserror:&error];
-
NSAssert(store!=nil,@"Error initializing PSC: %@\n%@",[errorlocalizedDescription],[erroruserInfo]);
-
});
-
}
在coredata中查询数据 通常用NSFetchedResultsController 查询结果控制器 管理coredata查询结果 它能节省内存 不会一下把所有数据都加载到内存中
经常和uitableview 联合使用 大概的步骤如下:
首先遵守代理
NSFetchedResultsControllerDelegate
-(NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController ==nil) {
//单例
CoreDataStroge *coreDataStroge = [CoreDataStrogesharedCoreDataStroge];
[coreDataStroge createContextWithModelName:@"lianxin"andDBName:@"lianxin.sqlite"];
//实例化一个对象
NSFetchRequest *fetchRequest = [[NSFetchRequestalloc]init];
NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Person"inManagedObjectContext:coreDataStroge.managedObjectContext];
//指定一个实体
[fetchRequest setEntity:entity];
// Specify criteria for filtering which objects to fetch查询条件可选
NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"name contains %@ ",@"zhangsan"];
[fetchRequest setPredicate:predicate];
// Specify how the fetched objects should be sorted必须指定
NSSortDescriptor *sortDescriptor = [[NSSortDescriptoralloc]initWithKey:@"name"
ascending:YES];
[fetchRequest setSortDescriptors:[NSArrayarrayWithObjects:sortDescriptor,nil]];
//执行查询 在需要的时候执行查询
// NSError *error = nil;
// NSArray *fetchedObjects = [<#context#> executeFetchRequest:fetchRequest error:&error];
// if (fetchedObjects == nil) {
// <#Error handling code#>
// }
//
/*----------------以上代码可以通过一个敲 fecth 有块代码直接生成-------------*/
_fetchedResultsController = [[NSFetchedResultsControlleralloc]initWithFetchRequest:fetchRequestmanagedObjectContext:coreDataStroge.managedObjectContextsectionNameKeyPath:nilcacheName:nil];
_fetchedResultsController.delegate =self;
}
return_fetchedResultsController;
}
最常用的代理方法: 一下参考自点击打开链接
//当数据发生变化时,点对点的更新tableview,这样大大的提高了更新效率
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
switch (type) {
case NSFetchedResultsChangeInsert:
[self.contentTableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:newIndexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.contentTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
{
[self.contentTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
[self.contentTableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:newIndexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
}
break;
case NSFetchedResultsChangeUpdate:
{
ContentCell * cell1 = (ContentCell *)[self.contentTableView cellForRowAtIndexPath:indexPath];
Student * stu = (Student *)[controller objectAtIndexPath:indexPath];
[cell1 showModel:stu];
}
break;
default:
break;
}
}
//点对点的更新section
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[self.contentTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.contentTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
//此方法执行时,说明数据已经发生了变化,通知tableview开始更新UI
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.contentTableView beginUpdates];
}
//结束更新
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.contentTableView endUpdates];
}