[IOS开发进阶与实战]第一天:CoreData的运行机制
1.数据模型NSManagedObjectModel的建立
- 1.- (NSManagedObjectModel *)managedObjectModel
- {
- if (_managedObjectModel != nil) {
- return _managedObjectModel;
- }
- NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataApp" withExtension:@"momd"];//加载我们的 modeld文件 得到modelURL
- _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; //获得有实体类型的Model
- return _managedObjectModel;
- }
这里使用了懒加载,就是说第一次加载之后,以后就不会再次加载,除非这个模型被删除了.
然后根据我们文件中的 CoreDataApp.momd 文件名字进行加载,得到 模型的URL.
最后通过URL 就可以得到我们的 managedObjectModel.
2.持久化存储的设置(就相当于我们的所要存储地方的文件)
- - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
- { //持久化存储控制器
- if (_persistentStoreCoordinator != nil) {
- return _persistentStoreCoordinator;
- }
- NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataApp.sqlite"];//app的存储位置,得到存储位置的URL
- NSError *error = nil;
- _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];//加载上面的定义好的模型
- if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
- //设置存储方式,存储位置.得到定义好的 持久化存储位置
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- return _persistentStoreCoordinator;
- }
首先得到我们的存储位置,制作成 URL .然后依赖于模型 制作我们的持久化管理器.
然后把我们的存储位置植入到我们的持久化管理器中.对错误进行处理 .
3.
- - (NSManagedObjectContext *)managedObjectContext
- {
- if (_managedObjectContext != nil) {
- return _managedObjectContext;
- }
- NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
- if (coordinator != nil) {
- _managedObjectContext = [[NSManagedObjectContext alloc] init]; //加载我们的定义好的模型和持久化存储位置,得到我们的上下文.
- [_managedObjectContext setPersistentStoreCoordinator:coordinator];
- }
- return _managedObjectContext;
- }
4.
- 4.app中断时候的保存
- - (void)applicationWillTerminate:(UIApplication *)application
- {
- // Saves changes in the application's managed object context before the application terminates.
- [self saveContext];
- }
- - (void)saveContext
- {
- NSError *error = nil;
- NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
- if (managedObjectContext != nil) {
- if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
- // Replace this implementation with code to handle the error appropriately.
- // 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.
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- }
- }
5.
- //5.按钮的添加和事件触发
- - (void)insertNewObject:(id)sender
- {
- NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
- NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
- NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
- // If appropriate, configure the new managed object.
- // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
- [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
- // Save the context.
- NSError *error = nil;
- if (![context save:&error]) {
- // Replace this implementation with code to handle the error appropriately.
- // 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.
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- }
- //6.请求控制器的实现
- - (NSFetchedResultsController *)fetchedResultsController
- {
- if (_fetchedResultsController != nil) {
- return _fetchedResultsController;
- }
- NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];//请求
- // Edit the entity name as appropriate.
- NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];//依赖上下文实体的名称
- [fetchRequest setEntity:entity]; //对请求设置具体实体的描述
- // Set the batch size to a suitable number.
- [fetchRequest setFetchBatchSize:20]; //每次能够取出20条记录.
- // Edit the sort key as appropriate.
- NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];//设置实体属性的key.设定排序规则
- NSArray *sortDescriptors = @[sortDescriptor];
- [fetchRequest setSortDescriptors:sortDescriptors];//添加实体的属性到请求中
- // Edit the section name key path and cache name if appropriate.
- // nil for section name key path means "no sections".
- NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];//创建请求控制器.
- aFetchedResultsController.delegate = self;
- self.fetchedResultsController = aFetchedResultsController;
- NSError *error = nil;
- if (![self.fetchedResultsController performFetch:&error]) {
- // Replace this implementation with code to handle the error appropriately.
- // 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.
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- return _fetchedResultsController;
- }
7.协议的实现
- #pragma mark - Fetched results controller
- - (NSFetchedResultsController *)fetchedResultsController
- {
- if (_fetchedResultsController != nil) {
- return _fetchedResultsController;
- }
- NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];//请求
- // Edit the entity name as appropriate.
- NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];//依赖上下文实体的名称
- [fetchRequest setEntity:entity]; //对请求设置具体实体的描述
- // Set the batch size to a suitable number.
- [fetchRequest setFetchBatchSize:20];
- // Edit the sort key as appropriate.
- NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];//设置实体的属性名称
- NSArray *sortDescriptors = @[sortDescriptor];
- [fetchRequest setSortDescriptors:sortDescriptors];//添加实体的属性到请求中
- // Edit the section name key path and cache name if appropriate.
- // nil for section name key path means "no sections".
- NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];//创建请求控制器.
- aFetchedResultsController.delegate = self;//NSFetchedResultsControllerDelegate
- self.fetchedResultsController = aFetchedResultsController;
- NSError *error = nil;
- if (![self.fetchedResultsController performFetch:&error]) {
- // Replace this implementation with code to handle the error appropriately.
- // 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.
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- return _fetchedResultsController;
- }
- - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
- {
- [self.tableView beginUpdates];
- }
- - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
- atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
- {
- switch(type) {
- case NSFetchedResultsChangeInsert:
- [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
- break;
- case NSFetchedResultsChangeDelete:
- [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
- break;
- }
- }
- - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
- atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
- newIndexPath:(NSIndexPath *)newIndexPath
- {
- UITableView *tableView = self.tableView;
- switch(type) {
- case NSFetchedResultsChangeInsert:
- [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
- break;
- case NSFetchedResultsChangeDelete:
- [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
- break;
- case NSFetchedResultsChangeUpdate:
- [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
- break;
- case NSFetchedResultsChangeMove:
- [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
- [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
- break;
- }
- }
- - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
- {
- [self.tableView endUpdates];
- }
- /*
- // 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.
- - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
- {
- // In the simplest, most efficient, case, reload the table view.
- [self.tableView reloadData];
- }
- */
- - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
- {
- NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
- cell.textLabel.text = [[object valueForKey:@"timeStamp"] description];
- }
[IOS开发进阶与实战]第一天:CoreData的运行机制的更多相关文章
- iOS开发进阶
<iOS开发进阶>基本信息作者: 唐巧 出版社:电子工业出版社ISBN:9787121247453上架时间:2014-12-26出版日期:2015 年1月开本:16开页码:268版次:1- ...
- iOS开发进阶(唐巧)读书笔记(一)
如何提高iOS开发技能 1.阅读博客:https://github.com/tangqiaoboy/iOSBlogCN 40多位iOS开发博主的博客地址 2.读书:每年阅读一本高质量的iOS开发书籍 ...
- 解析iOS开发中的FirstResponder第一响应对象
1. UIResonder 对于C#里所有的控件(例如TextBox),都继承于Control类.而Control类的继承关系如下: 代码如下: System.Object System.Marsha ...
- iOS开发:保持程序在后台长时间运行
iOS开发:保持程序在后台长时间运行 2014 年 5 月 26 日 / NIVALXER / 0 COMMENTS iOS为了让设备尽量省电,减少不必要的开销,保持系统流畅,因而对后台机制采用墓碑式 ...
- Chrome扩展开发之二——Chrome扩展中脚本的运行机制和通信方式
目录: 0.Chrome扩展开发(Gmail附件管理助手)系列之〇——概述 1.Chrome扩展开发之一——Chrome扩展的文件结构 2.Chrome扩展开发之二——Chrome扩展中脚本的运行机制 ...
- 《iOS开发进阶》书籍目录
第一部分:iOS开发工具 第二部分:iOS开发实践 第10章 理解内存管理 10.1 引用计数 10.1.1 什么是引用计数,原理是什么 10.1.2 我们为什么需要引用计数 10.1.3 不要向已经 ...
- iOS开发进阶之 UIWebView
刚接触IOS开发1年多,现在对于混合式移动端开发越来越流行,因为开发成本上.速度上都比传统的APP开发要好,混合式开发是传统模式与PC网页端相结合的模式.那么提到了 APP的混合模式开发,在Andro ...
- 【原】iOS开发进阶(唐巧)读书笔记(二)
第三部分:iOS开发底层原理 1.Objective-C对象模型 1.1 isa指针 NSObject.h部分代码: NS_ROOT_CLASS @interface NSObject <NSO ...
- iOS开发进阶--1.多线程简介
学习是由已知的知识模型推理未知的知识模型的的过程. 本文适合学习完objective-c基础,想进一步提高做iOS开发的同学阅读. 在说线程的时候,我们先看看进程. 1.进程 每一个运行在系统中的应用 ...
随机推荐
- SGU Volume 2
SGU200.Cracking RSA------------------------★高斯消元 SGU207.Robbers -------------------------------数论 SG ...
- PHP程序开发人员要掌握的知识
文件目录处理函数包80%以上的函数的功能的灵活运用. 日期时间函数中的80%以上的函数的功能的灵活运用 数学函数库中的100%的内容. 网络库中的60%以上的内容,对各个函数的功能比较熟悉. 字符串处 ...
- 《React-Native系列》38、 ReactNative混合组件封装
在我们做ReactNative项目的过程中,我们会发现由ReactNative提供给我们的组件或API往往满足不了我们的需求,常常需要我们自己去封装Native组件. 今天我们介绍下如果封装一个简单的 ...
- Android PackageManager packages.xml文件格式
packages.xml文件存放在/data/system目录下 该文件记录了系统中所有应用程序的包管理相关信息 PmS根据该文件进行包管理的各种操作 标签名称 所包含的值举例 last- ...
- 学习Swift--下标脚本
下标脚本 下标脚本可以定义在类(Class).结构体(structure)和枚举(enumeration)这些目标中,可以认为是访问集合(collection),列表(list)或序列(sequenc ...
- js共享onload事件
问题:通过js进行事件绑定,必须在HTML文档加载完成后再执行js脚本,否则可能因DOM不完整导致无法完成预计的效果,但对于不同的需求如何选用最佳的实现方式呢,这里做了整理,可以做参考. 一.对于小型 ...
- seajs的spm使用
压缩JS文件 只需要执行这个命令即可 spm build xxx.js 这时候你将得到一个压缩过的__build/xxx.js文件 合并JS文件 如果希望将JS文件中require的其他模块都合并到这 ...
- Choose the best route
hdu 2680:http://acm.hdu.edu.cn/showproblem.php?pid=2680 这道题值得一提的两点:在图论中注意重边问题是必须的,有向无向也是同等重要的,如这道题 f ...
- Android 两个Activity进行数据传送 发送
Activity1:: Intent intent= new Intent(this, OtherActivity.class); String name = "heyiyong" ...
- Bitmap介绍
转自:http://blog.csdn.net/xgdofull/article/details/5424611 简单的说就是用数组存放若有数据就标志为1或true,若不存在标志为0或false.比如 ...