iOS Core Data简单演练

本文详细介绍如何使用 Core Data 进行数据存储与管理,包括初始化设置、数据库创建过程及查询操作等核心步骤。此外,还提供了利用 NSFetchedResultsController 实现 UITableView 动态数据更新的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

先贴一个苹果官方的出事后一个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];
}





 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值