1、简介
Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。简单地用下图描述下它的作用:
左边是关系模型,即数据库,数据库里面有张person表,person表里面有id、name、age三个字段,而且有2条记录;
右边是对象模型,可以看到,有2个OC对象;
利用Core Data框架,我们就可以轻松地将数据库里面的2条记录转换成2个OC对象,也可以轻松地将2个OC对象保存到数据库中,变成2条表记录,而且不用写一条SQL语句。
2、常用类
(1)NSManagedObjectModel(被管理的对象模型)
相当于实体,不过它包含 了实体间的关系
(2)NSManagedObjectContext(被管理的对象上下文)
操作实际内容
作用:插入数据 查询 更新 删除
(3)NSPersistentStoreCoordinator(持久化存储助理)
相当于数据库的连接器
(4)NSFetchRequest(获取数据的请求)
相当于查询语句
(5)NSPredicate(相当于查询条件)
(6)NSEntityDescription(实体结构)
(7)后缀名为.xcdatamodel的包 (模型文件)
里面的.xcdatamodel文件,用数据模型编辑器编辑
编译后为.momd或.mom文件,这就是为什么文件中没有这个东西,而我们的程序中用到这个东西而不会报错的原因
3、类之间的关系如下图
4、创建模型文件
(1) 刚开是创建工程的时候,如果选择了coreData,系统会自动创建一个以工程名命名的模型文件并在appdelegate里创建CoreData所需的对象
(2) 自己手动创建模型文件
![](http://images.cnitblog.com/blog/497279/201302/27161628-80ca65b3ecdc4aadb29e6e3e9788ca15.png)
![](http://images.cnitblog.com/blog/497279/201302/27161647-30873f79f4ad4aa18ddf870f2478c405.png)
2.添加实体
![](http://images.cnitblog.com/blog/497279/201302/27161711-eca8497c327340a19ac7d6a5fe92d4f2.png)
3.添加Person的2个基本属性
![](http://images.cnitblog.com/blog/497279/201302/27161732-f8b583bc264f41ffb5f7c97ac905c5c8.png)
4.添加Card的1个基本属性
![](http://images.cnitblog.com/blog/497279/201302/27161740-e93feff9252c4481b8a38eaa57626ee7.png)
5.建立Card和Person的关联关系
右图中的表示Card中有个Person类型的person属性,目的就是建立Card跟Person之间的一对一关联关系(建议补上这一项),在Person中加上Inverse属性后,你会发现Card中Inverse属性也自动补上了
这里详细介绍一下关系:1:1 或者 1;N 、N:N等关系
点击创建的关系,在属性面板中设置,设置项如下图:
1、设置对应关系:Type
To One: 对应1。
To Many:对应N。
2、设置删除主题时的方式 Delete Rule
NO Aciton :主体删除时,关联的目标实体没有任何变化。
Nullify:主体删除时,关联的目标实体的外键值被置为Null。
Cascade:主体被删除时,关联的目标实体也被删除。
Deny:删除主体时,关联的实体依然存在的时候,删除失败,必须先删除关联的目标实体,然后才能删除实体。
5、CoreData相关对象创建的代码
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;
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.
[selfsaveContext];
}
#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 "com.zhidong.Books" in the application's documents directory.
return [[[NSFileManagerdefaultManager]URLsForDirectory:NSDocumentDirectoryinDomains: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 = [[NSBundlemainBundle]URLForResource:@"Books"withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModelalloc]initWithContentsOfURL:modelURL];
return_managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator !=nil) {
return_persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:[selfmanagedObjectModel]];
NSURL *storeURL = [[selfapplicationDocumentsDirectory]URLByAppendingPathComponent:@"Books.sqlite"];
NSError *error = nil;
NSString *failureReason =@"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURLoptions:nilerror:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionarydictionary];
dict[NSLocalizedDescriptionKey] =@"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSErrorerrorWithDomain:@"YOUR_ERROR_DOMAIN"code:9999userInfo: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, [erroruserInfo]);
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 = [selfpersistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContextalloc]init];
[_managedObjectContextsetPersistentStoreCoordinator:coordinator];
return_managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext =self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContextsave:&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, [erroruserInfo]);
abort();
}
}
}
6、执行语句的代码
1、带有条件的查询:
NSFetchRequest *request = [[NSFetchRequestalloc]init];
NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"NKBooks"inManagedObjectContext:self.appdelegate.managedObjectContext];
[requestsetEntity:entity];
request.predicate = [NSPredicatepredicateWithFormat:@"author=%@",self.author];
NSLog(@"名字:%@",self.author.name);
NSError *error =nil;
self.bookArray = [[self.appdelegate.managedObjectContextexecuteFetchRequest:requesterror:&error]mutableCopy];
if (self.bookArray ==nil) {
NSLog(@"获取FKBook实体时出错: %@,%@",error,[error userInfo]);
}
2、删除
NKAuthor *author =self.authorArray[indexPath.row];
[self.appDelegate.managedObjectContextdeleteObject:author];
NSError *error;
//保存删除操作,如果出现错误,显示错误信息
if (![self.appDelegate.managedObjectContextsave:&error])
{
NSLog(@"删除FKAuthor实体出错:%@,%@",error,[erroruserInfo]);
}
// 从authorArray集合中删除该元素
[self.authorArrayremoveObject:author];
3、插入
NKAuthor *author = [NSEntityDescriptioninsertNewObjectForEntityForName:@"NKAuthor"inManagedObjectContext:self.appDelegate.managedObjectContext];
author.name = authorName;
author.authorDesc = authorDesc;
NSError *error =nil;
if ([self.appDelegate.managedObjectContextsave:&error]) {
// 使用UIActionSheet提示添加成功
[[[UIActionSheetalloc]initWithTitle:@"添加成功"delegate:nil
cancelButtonTitle:nildestructiveButtonTitle:@"确定"
otherButtonTitles:nil,nil]showInView:self.view];
[self.navigationControllerpopViewControllerAnimated:YES];
}else{
NSLog(@"添加FKAuthor实体出错: %@,%@" , error ,[error userInfo]);
}
4、修改
//获取将要删除的作者
FKAuthor* deleteAuthor = [authorArrayobjectAtIndex:rowNo];
deleteAuthor.name =@"就是你呀";
NSError *error;
//保存修改操作,如果出现错误,显示错误信息
if (![self.appDelegate.managedObjectContextsave:&error])
{
NSLog(@"删除FKAuthor实体出错:%@,%@",error,[erroruserInfo]);
}