1.数据模型NSManagedObjectModel的建立

  1. 1.- (NSManagedObjectModel *)managedObjectModel
  2. {
  3. if (_managedObjectModel != nil) {
  4. return _managedObjectModel;
  5. }
  6. NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataApp" withExtension:@"momd"];//加载我们的 modeld文件 得到modelURL
  7. _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; //获得有实体类型的Model
  8. return _managedObjectModel;
  9. }

这里使用了懒加载,就是说第一次加载之后,以后就不会再次加载,除非这个模型被删除了.

然后根据我们文件中的 CoreDataApp.momd 文件名字进行加载,得到 模型的URL.

最后通过URL 就可以得到我们的 managedObjectModel.

2.持久化存储的设置(就相当于我们的所要存储地方的文件)

  1. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
  2. { //持久化存储控制器
  3. if (_persistentStoreCoordinator != nil) {
  4. return _persistentStoreCoordinator;
  5. }
  6.  
  7. NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataApp.sqlite"];//app的存储位置,得到存储位置的URL
  8.  
  9. NSError *error = nil;
  10. _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];//加载上面的定义好的模型
  11. if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
  12. //设置存储方式,存储位置.得到定义好的 持久化存储位置
  13. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  14. abort();
  15. }
  16.  
  17. return _persistentStoreCoordinator;
  18. }

首先得到我们的存储位置,制作成 URL .然后依赖于模型 制作我们的持久化管理器.

然后把我们的存储位置植入到我们的持久化管理器中.对错误进行处理 .

3.

  1. - (NSManagedObjectContext *)managedObjectContext
  2. {
  3. if (_managedObjectContext != nil) {
  4. return _managedObjectContext;
  5. }
  6.  
  7. NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  8. if (coordinator != nil) {
  9. _managedObjectContext = [[NSManagedObjectContext alloc] init]; //加载我们的定义好的模型和持久化存储位置,得到我们的上下文.
  10. [_managedObjectContext setPersistentStoreCoordinator:coordinator];
  11. }
  12. return _managedObjectContext;
  13. }

4.

  1. 4.app中断时候的保存
  2. - (void)applicationWillTerminate:(UIApplication *)application
  3. {
  4. // Saves changes in the application's managed object context before the application terminates.
  5. [self saveContext];
  6. }
  7.  
  8. - (void)saveContext
  9. {
  10. NSError *error = nil;
  11. NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
  12. if (managedObjectContext != nil) {
  13. if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
  14. // Replace this implementation with code to handle the error appropriately.
  15. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  16. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  17. abort();
  18. }
  19. }
  20. }

5.

  1. //5.按钮的添加和事件触发
  2. - (void)insertNewObject:(id)sender
  3. {
  4. NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
  5. NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
  6. NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
  7.  
  8. // If appropriate, configure the new managed object.
  9. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
  10. [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
  11.  
  12. // Save the context.
  13. NSError *error = nil;
  14. if (![context save:&error]) {
  15. // Replace this implementation with code to handle the error appropriately.
  16. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  17. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  18. abort();
  19. }
  20. }
  1. //6.请求控制器的实现
  2. - (NSFetchedResultsController *)fetchedResultsController
  3. {
  4. if (_fetchedResultsController != nil) {
  5. return _fetchedResultsController;
  6. }
  7.  
  8. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];//请求
  9. // Edit the entity name as appropriate.
  10. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];//依赖上下文实体的名称
  11. [fetchRequest setEntity:entity]; //对请求设置具体实体的描述
  12.  
  13. // Set the batch size to a suitable number.
  14. [fetchRequest setFetchBatchSize:20]; //每次能够取出20条记录.
  15.  
  16. // Edit the sort key as appropriate.
  17. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];//设置实体属性的key.设定排序规则
  18. NSArray *sortDescriptors = @[sortDescriptor];
  19.  
  20. [fetchRequest setSortDescriptors:sortDescriptors];//添加实体的属性到请求中
  21.  
  22. // Edit the section name key path and cache name if appropriate.
  23. // nil for section name key path means "no sections".
  24. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];//创建请求控制器.
  25. aFetchedResultsController.delegate = self;
  26. self.fetchedResultsController = aFetchedResultsController;
  27.  
  28. NSError *error = nil;
  29. if (![self.fetchedResultsController performFetch:&error]) {
  30. // Replace this implementation with code to handle the error appropriately.
  31. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  32. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  33. abort();
  34. }
  35.  
  36. return _fetchedResultsController;
  37. }

7.协议的实现

  1. #pragma mark - Fetched results controller
  2.  
  3. - (NSFetchedResultsController *)fetchedResultsController
  4. {
  5. if (_fetchedResultsController != nil) {
  6. return _fetchedResultsController;
  7. }
  8.  
  9. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];//请求
  10. // Edit the entity name as appropriate.
  11. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];//依赖上下文实体的名称
  12. [fetchRequest setEntity:entity]; //对请求设置具体实体的描述
  13.  
  14. // Set the batch size to a suitable number.
  15. [fetchRequest setFetchBatchSize:20];
  16.  
  17. // Edit the sort key as appropriate.
  18. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];//设置实体的属性名称
  19. NSArray *sortDescriptors = @[sortDescriptor];
  20.  
  21. [fetchRequest setSortDescriptors:sortDescriptors];//添加实体的属性到请求中
  22.  
  23. // Edit the section name key path and cache name if appropriate.
  24. // nil for section name key path means "no sections".
  25. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];//创建请求控制器.
  26. aFetchedResultsController.delegate = self;//NSFetchedResultsControllerDelegate
  27. self.fetchedResultsController = aFetchedResultsController;
  28.  
  29. NSError *error = nil;
  30. if (![self.fetchedResultsController performFetch:&error]) {
  31. // Replace this implementation with code to handle the error appropriately.
  32. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  33. NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  34. abort();
  35. }
  36.  
  37. return _fetchedResultsController;
  38. }
  39.  
  40. - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
  41. {
  42. [self.tableView beginUpdates];
  43. }
  44.  
  45. - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
  46. atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
  47. {
  48. switch(type) {
  49. case NSFetchedResultsChangeInsert:
  50. [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
  51. break;
  52.  
  53. case NSFetchedResultsChangeDelete:
  54. [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
  55. break;
  56. }
  57. }
  58.  
  59. - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
  60. atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
  61. newIndexPath:(NSIndexPath *)newIndexPath
  62. {
  63. UITableView *tableView = self.tableView;
  64.  
  65. switch(type) {
  66. case NSFetchedResultsChangeInsert:
  67. [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
  68. break;
  69.  
  70. case NSFetchedResultsChangeDelete:
  71. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
  72. break;
  73.  
  74. case NSFetchedResultsChangeUpdate:
  75. [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
  76. break;
  77.  
  78. case NSFetchedResultsChangeMove:
  79. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
  80. [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
  81. break;
  82. }
  83. }
  84.  
  85. - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
  86. {
  87. [self.tableView endUpdates];
  88. }
  89.  
  90. /*
  91. // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
  92.  
  93. - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
  94. {
  95. // In the simplest, most efficient, case, reload the table view.
  96. [self.tableView reloadData];
  97. }
  98. */
  99.  
  100. - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
  101. {
  102. NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
  103. cell.textLabel.text = [[object valueForKey:@"timeStamp"] description];
  104. }

[IOS开发进阶与实战]第一天:CoreData的运行机制的更多相关文章

  1. iOS开发进阶

    <iOS开发进阶>基本信息作者: 唐巧 出版社:电子工业出版社ISBN:9787121247453上架时间:2014-12-26出版日期:2015 年1月开本:16开页码:268版次:1- ...

  2. iOS开发进阶(唐巧)读书笔记(一)

    如何提高iOS开发技能 1.阅读博客:https://github.com/tangqiaoboy/iOSBlogCN 40多位iOS开发博主的博客地址 2.读书:每年阅读一本高质量的iOS开发书籍 ...

  3. 解析iOS开发中的FirstResponder第一响应对象

    1. UIResonder 对于C#里所有的控件(例如TextBox),都继承于Control类.而Control类的继承关系如下: 代码如下: System.Object System.Marsha ...

  4. iOS开发:保持程序在后台长时间运行

    iOS开发:保持程序在后台长时间运行 2014 年 5 月 26 日 / NIVALXER / 0 COMMENTS iOS为了让设备尽量省电,减少不必要的开销,保持系统流畅,因而对后台机制采用墓碑式 ...

  5. Chrome扩展开发之二——Chrome扩展中脚本的运行机制和通信方式

    目录: 0.Chrome扩展开发(Gmail附件管理助手)系列之〇——概述 1.Chrome扩展开发之一——Chrome扩展的文件结构 2.Chrome扩展开发之二——Chrome扩展中脚本的运行机制 ...

  6. 《iOS开发进阶》书籍目录

    第一部分:iOS开发工具 第二部分:iOS开发实践 第10章 理解内存管理 10.1 引用计数 10.1.1 什么是引用计数,原理是什么 10.1.2 我们为什么需要引用计数 10.1.3 不要向已经 ...

  7. iOS开发进阶之 UIWebView

    刚接触IOS开发1年多,现在对于混合式移动端开发越来越流行,因为开发成本上.速度上都比传统的APP开发要好,混合式开发是传统模式与PC网页端相结合的模式.那么提到了 APP的混合模式开发,在Andro ...

  8. 【原】iOS开发进阶(唐巧)读书笔记(二)

    第三部分:iOS开发底层原理 1.Objective-C对象模型 1.1 isa指针 NSObject.h部分代码: NS_ROOT_CLASS @interface NSObject <NSO ...

  9. iOS开发进阶--1.多线程简介

    学习是由已知的知识模型推理未知的知识模型的的过程. 本文适合学习完objective-c基础,想进一步提高做iOS开发的同学阅读. 在说线程的时候,我们先看看进程. 1.进程 每一个运行在系统中的应用 ...

随机推荐

  1. SGU Volume 2

    SGU200.Cracking RSA------------------------★高斯消元 SGU207.Robbers -------------------------------数论 SG ...

  2. PHP程序开发人员要掌握的知识

    文件目录处理函数包80%以上的函数的功能的灵活运用. 日期时间函数中的80%以上的函数的功能的灵活运用 数学函数库中的100%的内容. 网络库中的60%以上的内容,对各个函数的功能比较熟悉. 字符串处 ...

  3. 《React-Native系列》38、 ReactNative混合组件封装

    在我们做ReactNative项目的过程中,我们会发现由ReactNative提供给我们的组件或API往往满足不了我们的需求,常常需要我们自己去封装Native组件. 今天我们介绍下如果封装一个简单的 ...

  4. Android PackageManager packages.xml文件格式

    packages.xml文件存放在/data/system目录下    该文件记录了系统中所有应用程序的包管理相关信息    PmS根据该文件进行包管理的各种操作 标签名称 所包含的值举例 last- ...

  5. 学习Swift--下标脚本

    下标脚本 下标脚本可以定义在类(Class).结构体(structure)和枚举(enumeration)这些目标中,可以认为是访问集合(collection),列表(list)或序列(sequenc ...

  6. js共享onload事件

    问题:通过js进行事件绑定,必须在HTML文档加载完成后再执行js脚本,否则可能因DOM不完整导致无法完成预计的效果,但对于不同的需求如何选用最佳的实现方式呢,这里做了整理,可以做参考. 一.对于小型 ...

  7. seajs的spm使用

    压缩JS文件 只需要执行这个命令即可 spm build xxx.js 这时候你将得到一个压缩过的__build/xxx.js文件 合并JS文件 如果希望将JS文件中require的其他模块都合并到这 ...

  8. Choose the best route

    hdu 2680:http://acm.hdu.edu.cn/showproblem.php?pid=2680 这道题值得一提的两点:在图论中注意重边问题是必须的,有向无向也是同等重要的,如这道题 f ...

  9. Android 两个Activity进行数据传送 发送

    Activity1:: Intent intent= new Intent(this, OtherActivity.class); String name = "heyiyong" ...

  10. Bitmap介绍

    转自:http://blog.csdn.net/xgdofull/article/details/5424611 简单的说就是用数组存放若有数据就标志为1或true,若不存在标志为0或false.比如 ...