[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.进程 每一个运行在系统中的应用 ...
随机推荐
- ecmall 后台导航增加菜单
以我增加的团购为例: languages\sc-gbk\admin 中的default.lang.php 文件中底部增加变量值 'groupbuy'=>'团购', 'groupbuyord ...
- Linux下安装gcc 、g++ 、gfortran编译器
一.ubuntu下gcc/g++/gfortran的安装 1.安装 (1).gcc ubuntu下自带gcc编译器.可以通过“gcc -v”命令来查看是否安装. (2).g++ 安装g++编译器,可以 ...
- PHP扩展Redis编译安装
PHP扩展Redis编译安装 1.下载PHP官方Redis源码包 wget http://pecl.php.net/get/redis-2.2.4.tgz 注:我用的是Redhat系统,ubunt ...
- getInputStream与getReader方法
getInputStream 方法用于返回的一个代表实体内容的输入流对象,其类型为javax.servlet.ServletInputStream. getReader方法用于返回的一个代表实体内容的 ...
- Visual Studio C/C++ 编译器选项
优化- /O1 最小化空间 /O2 最大化速度/Ob<n> 内联扩展(默认 n=0) /Od 禁用优化(默认) ...
- vim配置-程序员【转】
Ubuntu11.10的vim升级后,版本为vi Improved 7.3.154功能很强大了.不过,程序员要根据自己的习惯配置好vimrc文件,是vim更加得心应手. 注:一般用户在自己的当前目录下 ...
- [BZOJ 1081] [SCOI2005] 超级格雷码 【找规律】
题目链接:BZOJ - 1081 备注:此题BZOJ上貌似没有 spj ,要把一般顺序的每个格雷码倒着输出...比如 0102 输出为 2010 题目分析 就是按照 Gray 码的生成方法写前几个出来 ...
- JSP环境配置
为免以后忘记,记下了. Jdk在C盘,tomcat在D盘. 1.JAVA_HOME C:\Program Files\Java\jdk1.7.0_07 2.CATALINA_HOME D:\apach ...
- Strongly connected
hdu4635:http://acm.hdu.edu.cn/showproblem.php?pid=4635 题意:给你一个有向图,然后问你最多可以加多少条边,是的原图不是一个强连通图. 题解:这一题 ...
- Hidden Password
zoj1729:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=729 题意:就是求字符串的最小表示,模板题. 题解:直接贴模板. ...