iOS Core Data简单演练

来源:互联网 发布:100m网络下载速度 编辑:程序博客网 时间:2024/05/01 17:50

在看之前请先查看这篇内容点击打开链接  这里面对一些基本的操作已经很全面。我自己的学习也是总这么文章开始的。

先贴一个苹果官方的出事后一个coredata的方法

  1. -(void)initializeCoreData
  2. {
  3. //实例化数据模型
  4. NSURL*modelURL=[[NSBundlemainBundle]URLForResource:@"DataModel"withExtension:@"momd"];
  5. NSManagedObjectModel*mom=[[NSManagedObjectModelalloc]initWithContentsOfURL:modelURL];
  6. NSAssert(mom!=nil,@"Error initializing Managed Object Model");

  7. //实例化持久化存储调度器
  8. NSPersistentStoreCoordinator*psc=[[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:mom];
//实例化被管理对象上下文
  1. NSManagedObjectContext*moc=[[NSManagedObjectContextalloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
  2. //指定上下文的调度器
  3. [mocsetPersistentStoreCoordinator:psc];
  4. [selfsetManagedObjectContext:moc];
  5. //获取数据库路径和指定数据库名称
  6. NSFileManager*fileManager=[NSFileManagerdefaultManager];
  7. //注意这儿需要的是文件路径
  8. NSURL*documentsURL=[[fileManagerURLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask]lastObject];
  9. NSURL*storeURL=[documentsURLURLByAppendingPathComponent:@"DataModel.sqlite"];
  10. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^(void){
  11. NSError*error=nil;
  12. NSPersistentStoreCoordinator*psc=[[selfmanagedObjectContext]persistentStoreCoordinator];
  13. //添加持久化存储 创建数据库
  14. NSPersistentStore*store=[pscaddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURLoptions:optionserror:&error];
  15. NSAssert(store!=nil,@"Error initializing PSC: %@\n%@",[errorlocalizedDescription],[erroruserInfo]);
  16. });
  17. }

如果我们有很多不同的模型,并且数据库文件也不确定 可以把上面的方法抽象成一个单例中得方法

  1. -(void)initializeCoreDataWithModelName:(NSString *)modelName andDBName:(NSString *)dbName
  2. {
  3. //实例化数据模型
  4. NSURL*modelURL=[[NSBundlemainBundle]URLForResource:modelNamewithExtension:@"momd"];
  5. NSManagedObjectModel*mom=[[NSManagedObjectModelalloc]initWithContentsOfURL:modelURL];
  6. NSAssert(mom!=nil,@"Error initializing Managed Object Model");

  7. //实例化持久化存储调度器
  8. NSPersistentStoreCoordinator*psc=[[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:mom];
//实例化被管理对象上下文
  1. NSManagedObjectContext*moc=[[NSManagedObjectContextalloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
  2. //指定上下文的调度器
  3. [mocsetPersistentStoreCoordinator:psc];
  4. [selfsetManagedObjectContext:moc];
  5. //获取数据库路径和指定数据库名称
  6. NSFileManager*fileManager=[NSFileManagerdefaultManager];
  7. //注意这儿需要的是文件路径
  8. NSURL*documentsURL=[[fileManagerURLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask]lastObject];
  9. NSURL*storeURL=[documentsURLURLByAppendingPathComponent:dbName];
  10. //这样做的目的 可能是为了快速返回上下文 减少启动时间 (个人猜想)
  11. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^(void){
  12. NSError*error=nil;
  13. NSPersistentStoreCoordinator*psc=[[selfmanagedObjectContext]persistentStoreCoordinator];
  14. //添加持久化存储 创建数据库
  15. NSPersistentStore*store=[pscaddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURLoptions:optionserror:&error];
  16. NSAssert(store!=nil,@"Error initializing PSC: %@\n%@",[errorlocalizedDescription],[erroruserInfo]);
  17. });
  18. }
下面主要介绍一下coredata的查询

在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];}





 



1 0