简介
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语句。
模型文件
在Core Data,需要进行映射的对象称为实体(entity),而且需要使用Core Data的模型文件来描述app中的所有实体和实体属性。这里以Person(人)和Card(身份证)2个实体为例子,先看看实体属性和实体之间的关联关系:

Person实体中有:name(姓名)、age(年龄)、card(身份证)三个属性
Card实体中有:no(号码)、person(人)两个属性
接下来看看创建模型文件的过程:
1.选择模板


2.添加实体

3.添加Person的2个基本属性

4.添加Card的1个基本属性

5.建立Card和Person的关联关系

右图中的
表示Card中有个Person类型的person属性,目的就是建立Card跟Person之间的一对一关联关系(建议补上这一项),在Person中加上Inverse属性后,你会发现Card中Inverse属性也自动补上了

了解NSManagedObject
1.通过Core Data从数据库取出的对象,默认情况下都是NSManagedObject对象

2.NSManagedObject的工作模式有点类似于NSDictionary对象,通过键-值对来存取所有的实体属性
1> setValue:forKey:存储属性值(属性名为key)
2> valueForKey:获取属性值(属性名为key)
CoreData中的核心对象

注:黑色表示类名,红色表示类里面的一个属性
开
发步骤总结:
1.初始化NSManagedObjectModel对象,加载模型文件,读取app中的所有实体信息
2.初始化NSPersistentStoreCoordinator对象,添加持久化库(这里采取SQLite数据库)
3.初始化NSManagedObjectContext对象,拿到这个上下文对象操作实体,进行CRUD操作
代码实现
先
添加CoreData.framework和导入主头文件<CoreData/CoreData.h>
1.搭建上下文环境
-
- NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
-
- NSPersistentStoreCoordinator *psc = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model] autorelease];
-
- NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.data"]];
-
- NSError *error = nil;
- NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
- if (store == nil) {
- [NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]];
- }
-
- NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
- context.persistentStoreCoordinator = psc;
-
2.添加数据到数据库
-
- NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
-
- [person setValue:@"MJ" forKey:@"name"];
- [person setValue:[NSNumber numberWithInt:27] forKey:@"age"];
-
- NSManagedObject *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:context];
- [card setValue:@"4414241933432" forKey:@"no"];
-
- [person setValue:card forKey:@"card"];
-
- NSError *error = nil;
- BOOL success = [context save:&error];
- if (!success) {
- [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
- }
-
3.从数据库中查询数据
-
- NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
-
- request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
-
- NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
- request.sortDescriptors = [NSArray arrayWithObject:sort];
-
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*Itcast-1*"];
- request.predicate = predicate;
-
- NSError *error = nil;
- NSArray *objs = [context executeFetchRequest:request error:&error];
- if (error) {
- [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
- }
-
- for (NSManagedObject *obj in objs) {
- NSLog(@"name=%@", [obj valueForKey:@"name"]
- }
注:Core Data不会根据实体中的关联关系立即获取相应的关联对象,比如通过Core Data取出Person实体时,并不会立即查询相关联的Card实体;当应用真的需要使用Card时,才会再次查询数据库,加载Card实体的信息。这个就是Core Data的延迟加载机制
4.删除数据库中的数据
-
- [context deleteObject:managedObject];
-
- NSError *error = nil;
- [context save:&error];
- if (error) {
- [NSException raise:@"删除错误" format:@"%@", [error localizedDescription]];
- }
打开CoreData的SQL语句输出开关
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
1> -com.apple.CoreData.SQLDebug
2> 1
创建NSManagedObject的子类
默认情况下,利用Core Data取出的实体都是NSManagedObject类型的,能够利用键-值对来存取数据。但是一般情况下,实体在存取数据的基础上,有时还需要添加一些业务方法来完成一些其他任务,那么就必须创建NSManagedObject的子类
选择模型文件

选择需要创建子类的实体

创建完毕后,多
了2个子类

文件内容展示:
Person.h
- #import <Foundation/Foundation.h>
- #import <CoreData/CoreData.h>
-
- @class Card;
-
- @interface Person : NSManagedObject
-
- @property (nonatomic, retain) NSString * name;
- @property (nonatomic, retain) NSNumber * age;
- @property (nonatomic, retain) Card *card;
-
- @end
Person.m
- #import "Person.h"
-
- @implementation Person
-
- @dynamic name;
- @dynamic age;
- @dynamic card;
-
- @end
Card.h
- #import <Foundation/Foundation.h>
- #import <CoreData/CoreData.h>
-
- @class Person;
-
- @interface Card : NSManagedObject
-
- @property (nonatomic, retain) NSString * no;
- @property (nonatomic, retain) Person *person;
-
- @end
Card.m
- #import "Card.h"
- #import "Person.h"
-
- @implementation Card
-
- @dynamic no;
- @dynamic person;
-
- @end
那么往数据库中添加数据的时候就应该写了:
- Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
- person.name = @"MJ";
- person.age = [NSNumber numberWithInt:27];
-
- Card *card = [NSEntityDescription insertNewObjectForEntityForName:@”Card" inManagedObjectContext:context];
- card.no = @”4414245465656";
- person.card = card;
-
说到这里,整个Core Data框架的入门就结束了,其实Core Data还远不止这些功能,它还支持自动撤销机制,一对多关联等,这里就不一一介绍了 Core Data入门,布布扣,bubuko.com
Core Data入门
原文:http://www.cnblogs.com/llios/p/3786290.html