关于Core Data的一些整理(一)
关于Core Data的一些整理(一)
在Xcode7.2中只有Mast-Debug和Single View中可以勾选Use Core Data
.xcdatamodeld
数据文件//Appdelegate.h中
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; - (void)saveContext;
- (NSURL *)applicationDocumentsDirectory; @end //Appdelegate.m中系统帮助生成的代码
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
} #pragma mark - Core Data stack @synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator; - (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "qq100858433.JMHitList" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
} - (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"JMHitList" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
} - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
} // Create the coordinator and store _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JMHitList.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code: userInfo:dict];
// Replace this 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 _persistentStoreCoordinator;
} - (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
} NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
} #pragma mark - Core Data Saving support - (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = 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();
}
}
} @end
假如你在.xcdatamodeld
中生成了如下实体和实体属性:

//从Core Data中获得已有数据
id appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
@try {
self.people = [NSMutableArray arrayWithArray:[managedContext executeFetchRequest:fetchRequest error:nil]];
}
@catch (NSException *exception) {
NSLog(@"Could not fetch %@", [exception userInfo]);
}
@finally {
NSLog(@"Fetch Successful");
} //为数据库添加实体实例
id appDelegate = [UIApplication sharedApplication].delegate;
//NSManagedObjectContext可以看做内存中用来处理managedObjects的暂存器
NSManagedObjectContext *mangedContext = [appDelegate managedObjectContext];
//下面两种方法都可以获得Person实体
// NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:mangedContext];
// NSManagedObject *person = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:mangedContext];
// [person setValue:name forKey:@"name"];
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:mangedContext];
[person setValue:name forKey:@"name"];
@try {
[mangedContext save:nil];
[self.people addObject:person];
}
@catch (NSException *exception) {
NSLog(@"Could not save %@", [exception userInfo]);
}
@finally {
NSLog(@"Save Successfullt!");
}
关于Core Data的一些整理(一)的更多相关文章
- 关于Core Data的一些整理(五)
关于Core Data的一些整理(五) 在Core Data中使用NSFetchedResultsController(以下简称VC)实现与TableView的交互,在实际中,使用VC有很多优点,其中 ...
- 关于Core Data的一些整理(四)
关于Core Data的一些整理(四) 调用Core Data文件中的Request模板进行条件匹配 //获取ObjectModel相当于获取Core Date文件 NSManagedObjectMo ...
- 关于Core Data的一些整理(三)
关于Core Data的一些整理(三) 关于Core Data Stack的四种类与它们的关系如下: NSManagedObjectModel NSPersistentStore NSPersiste ...
- 关于Core Data的一些整理(二)
关于Core Data的一些整理(二) 创建NSManagedObject的子类时,有一点是在这中间要强调的一点是,要不要勾选 Use scalar properties for primitive ...
- Core Data 学习简单整理01
Core Data是苹果针对Mac和iOS平台开发的一个框架, 通过CoreData可以在本地生成数据库sqlite,提供了ORM的功能,将对象和数据模型相互转换 . 通过Core Data管理和操作 ...
- 《驾驭Core Data》 第三章 数据建模
本文由海水的味道编译整理,请勿转载,请勿用于商业用途. 当前版本号:0.1.2 第三章数据建模 Core Data栈配置好之后,接下来的工作就是设计对象图,在Core Data框架中,对象图被表 ...
- 《驾驭Core Data》 第二章 Core Data入门
本文由海水的味道编译整理,请勿转载,请勿用于商业用途. 当前版本号:0.4.0 第二章 Core Data入门 本章将讲解Core Data框架中涉及的基本概念,以及一个简单的Core Data ...
- 《驾驭Core Data》 第一章 Core Data概述
<驾驭Core Data>系列教程综合了<Core Data for iOS>,<Learning Core Data for iOS>,<Core Data ...
- iOS之Core Data及其线程安全
一.简介 Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对 ...
随机推荐
- 通用GPIO模拟串口,提供源代码,本人经过测试OK(第一版)
--------------------------serial.h------------------------------------------ #ifndef _SERIAL_H_ #def ...
- JAVA NIO 简介(转)
1. 基本 概念 IO 是主存和外部设备 ( 硬盘.终端和网络等 ) 拷贝数据的过程. IO 是操作系统的底层功能实现,底层通过 I/O 指令进行完成. 所有语言运行时系统提供执行 I/O 较高级 ...
- 权重随机算法的java实现
一.概述 平时,经常会遇到权重随机算法,从不同权重的N个元素中随机选择一个,并使得总体选择结果是按照权重分布的.如广告投放.负载均衡等. 如有4个元素A.B.C.D,权重分别为1.2.3.4,随机结果 ...
- linux安装 Android Studio详细教程,支持性较差,需要安装最新底层库内核的linux
安装 Android Studio详细教程 libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1 jdk1.8.0_25 android-st ...
- Linux Shell编程(8)——变量详解
不同与许多其他的编程语言,Bash不以"类型"来区分变量.本质上来说,Bash变量是字符串,但是根据环境的不同,Bash允许变量有整数计算和比较.其中的决定因素是变量的值是不是只含 ...
- 杂题 UVAoj 10000 Longest Paths
Longest Paths It is a well known fact that some people do not have their social abilities complet ...
- 《ACM国际大学生程序设计竞赛题解Ⅰ》——基础编程题
这个专栏开始介绍一些<ACM国际大学生程序设计竞赛题解>上的竞赛题目,读者可以配合zju/poj/uva的在线测评系统提交代码(今天zoj貌似崩了). 其实看书名也能看出来这本书的思路,就 ...
- Period II - FZU 1901(KMP->next)
题目大意:给你一个字符串 S ,N = |S|,如果存在一个 P (1<=P<=N),并且满足 s[i] = s[P+i] (i = {0...N-P-1} ),求出来所有的 P 然后输出 ...
- Substrings - HDU 1238(最大共同子串)
题目大意:给你N个串,求出来他们的最大公共子串的长度(子串反过来也算他们的子串). 分析:很久以前就做过这道题,当时是用的strstr做的,不过相同的都是枚举了子串......还是很暴力,希望下次 ...
- 005_MyEclipse编码设置
方法一: 1.打开MyEclipse,windows---->Preferences打开"首选项"对话框. 2.左侧导航,导航中找到general---->Worksp ...