Core Data是iOS5之后才出現(xiàn)的一個(gè)框架,它提供了對(duì)象-關(guān)系映射(ORM)的功能,即能夠?qū)C對(duì)象轉(zhuǎn)化成數(shù)據(jù),保存在SQLite數(shù)據(jù)庫(kù)文件中,也能夠?qū)⒈4嬖跀?shù)據(jù)庫(kù)中的數(shù)據(jù)還原成OC對(duì)象。在此數(shù)據(jù)操作期間,我們不需要編寫(xiě)任何SQL語(yǔ)句,這個(gè)有點(diǎn)類似于著名的Hibernate持久化框架,不過(guò)功能肯定是沒(méi)有Hibernate強(qiáng)大的。簡(jiǎn)單地用下圖描述下它的作用:
左邊是關(guān)系模型,即數(shù)據(jù)庫(kù),數(shù)據(jù)庫(kù)里面有張person表,person表里面有id、name、age三個(gè)字段,而且有2條記錄;
利用Core Data框架,我們就可以輕松地將數(shù)據(jù)庫(kù)里面的2條記錄轉(zhuǎn)換成2個(gè)OC對(duì)象,也可以輕松地將2個(gè)OC對(duì)象保存到數(shù)據(jù)庫(kù)中,變成2條表記錄,而且不用寫(xiě)一條SQL語(yǔ)句。
2.NSManagedObject的工作模式有點(diǎn)類似于NSDictionary對(duì)象,通過(guò)鍵-值對(duì)來(lái)存取所有的實(shí)體屬性
2> valueForKey:獲取屬性值(屬性名為key)
CoreData中的核心對(duì)象

注:黑色表示類名,紅色表示類里面的一個(gè)屬性
開(kāi)發(fā)步驟總結(jié):
1.初始化NSManagedObjectModel對(duì)象,加載模型文件,讀取app中的所有實(shí)體信息
2.初始化NSPersistentStoreCoordinator對(duì)象,添加持久化庫(kù)(這里采取SQLite數(shù)據(jù)庫(kù))
3.初始化NSManagedObjectContext對(duì)象,拿到這個(gè)上下文對(duì)象操作實(shí)體,進(jìn)行CRUD操作
代碼實(shí)現(xiàn)
先添加CoreData.framework和導(dǎo)入主頭文件<CoreData/CoreData.h>

1.搭建上下文環(huán)境
- 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:@"添加數(shù)據(jù)庫(kù)錯(cuò)誤" format:@"%@", [error localizedDescription]];
- }
- NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
- context.persistentStoreCoordinator = psc;
2.添加數(shù)據(jù)到數(shù)據(jù)庫(kù)
- 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:@"訪問(wèn)數(shù)據(jù)庫(kù)錯(cuò)誤" format:@"%@", [error localizedDescription]];
- }
3.從數(shù)據(jù)庫(kù)中查詢數(shù)據(jù)
- 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:@"查詢錯(cuò)誤" format:@"%@", [error localizedDescription]];
- }
- for (NSManagedObject *obj in objs) {
- NSLog(@"name=%@", [obj valueForKey:@"name"]
- }
注:Core Data不會(huì)根據(jù)實(shí)體中的關(guān)聯(lián)關(guān)系立即獲取相應(yīng)的關(guān)聯(lián)對(duì)象,比如通過(guò)Core Data取出Person實(shí)體時(shí),并不會(huì)立即查詢相關(guān)聯(lián)的Card實(shí)體;當(dāng)應(yīng)用真的需要使用Card時(shí),才會(huì)再次查詢數(shù)據(jù)庫(kù),加載Card實(shí)體的信息。這個(gè)就是Core Data的延遲加載機(jī)制
4.刪除數(shù)據(jù)庫(kù)中的數(shù)據(jù)
- [context deleteObject:managedObject];
- NSError *error = nil;
- [context save:&error];
- if (error) {
- [NSException raise:@"刪除錯(cuò)誤" format:@"%@", [error localizedDescription]];
- }
打開(kāi)CoreData的SQL語(yǔ)句輸出開(kāi)關(guān)
1.打開(kāi)Product,點(diǎn)擊EditScheme...
2.點(diǎn)擊Arguments,在ArgumentsPassed On Launch中添加2項(xiàng)
1> -com.apple.CoreData.SQLDebug
2> 1


創(chuàng)建NSManagedObject的子類
默認(rèn)情況下,利用Core Data取出的實(shí)體都是NSManagedObject類型的,能夠利用鍵-值對(duì)來(lái)存取數(shù)據(jù)。但是一般情況下,實(shí)體在存取數(shù)據(jù)的基礎(chǔ)上,有時(shí)還需要添加一些業(yè)務(wù)方法來(lái)完成一些其他任務(wù),那么就必須創(chuàng)建NSManagedObject的子類

選擇模型文件

選擇需要?jiǎng)?chuàng)建子類的實(shí)體

創(chuàng)建完畢后,多了2個(gè)子類

文件內(nèi)容展示:
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
那么往數(shù)據(jù)庫(kù)中添加數(shù)據(jù)的時(shí)候就應(yīng)該寫(xiě)了:
- 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;
CoreData 從iOS 3.0 開(kāi)始 (orm的原理)
用coreData 來(lái)操作sqlite 對(duì)象 -> 調(diào)用插入方法
CoreData 是Mac OS X中Cocoa API的一部分, 首次出現(xiàn)在Mac OS 10.4 和iOS 3.0 中. 它提供了 對(duì)象- 關(guān)系映射 (ORM) 功能. 可以將OC對(duì)象轉(zhuǎn)化為數(shù)據(jù), 保存在SQLite數(shù)據(jù)庫(kù)文件中, 也能夠?qū)?shù)據(jù)庫(kù)的文件還原成OC對(duì)象. 在此期間, 我們不需要編寫(xiě)任何SQL語(yǔ)句.
可以簡(jiǎn)單的理解為Cocoa對(duì)SQLite的一層封裝.
CocoaData 好處:
一: 極大的減少M(fèi)odel層的代碼量.
二: 優(yōu)化了使用SQLite時(shí)候的性能.
三: 提供了可視化設(shè)計(jì).
NO.1 managedObjectContext 上下文對(duì)象 負(fù)責(zé)將我們要保存的對(duì)象存入到數(shù)據(jù)庫(kù)中, 或者從數(shù)據(jù)庫(kù)中取出數(shù)據(jù)
NO.2 managedObjectModel 管理對(duì)象模型 負(fù)責(zé)把我們?cè)?CoreDataDemo.xcdatamodeld 文件中添加的entity(實(shí)體)轉(zhuǎn)化為sqlite數(shù)據(jù)庫(kù)中的表.
NO.3 persistentStoreCoordinator 持久化存儲(chǔ)協(xié)調(diào)器 負(fù)責(zé)把要保存的數(shù)據(jù)(sqlite文件) 存儲(chǔ)到沙盒中某個(gè)位置.
@synthesize property 讓系統(tǒng)幫我們生成set get 方法
@dynamic name; // 不讓系統(tǒng)生成get和set方法 需要我們自己去實(shí)現(xiàn)
插入數(shù)據(jù):
// 插入操作
- (void)insertData
{
// 獲取到上下文對(duì)象
AppDelegate *delegate = [UIapplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.managedObjectContext;
// 創(chuàng)建一個(gè)要插入的對(duì)象
NSManagedObject *people = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:context];
[people setValue:@"王紅五" forKey:@"name"];
[people setValue:@(28) forKey:@"age"];
NSError *error = nil;
// 執(zhí)行保存的方法, 就會(huì)把剛才創(chuàng)建的對(duì)象保存到數(shù)據(jù)庫(kù)中
BOOL isSave = [context save:&error];
if (isSave) {
NSLog(@"insert success");
}else
{
NSLog(@"insert failed %@",error);
}
// 方法二
People *people1 = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:context];
people1.name = @"馬六六";
people1.age = @21;
NSError *error1 = nil;
[context save:&error1];
}
查詢操作:
- (void)queryData
{
// 獲取到上下文對(duì)象
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.managedObjectContext;
// 創(chuàng)建一個(gè)查詢的請(qǐng)求
NSFetchRequest *request = [[NSFetchRequest alloc]init];
// 設(shè)置要查詢哪一個(gè)實(shí)體(表)
request.entity = [NSEntityDescription entityForName:@"People" inManagedObjectContext:context];
// 排序?qū)ο?/span>
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
request.sortDescriptors = @[sort];
// 查詢條件
request.predicate = [NSPredicate predicateWithFormat:@"name like %@",@"馬*"];
// 調(diào)用查詢的方法
NSError *error = nil;
NSArray *array = [context executeFetchRequest:request error:&error];
for (People *p in array) {
NSLog(@"name %@ age %@",p.name,p.age);
// [self updateData:p];
[self deleteData:p];
}
}
修改(更新操作):
- (void)updateData: (People *)people
{
// 修改具體的值
people.age = @40;
// 獲取到上下文對(duì)象
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.managedObjectContext;
NSError *error = nil;
BOOL isOk = [context save:&error];
NSLog(@"%@",isOk == YES?@"保存成功":@"保存失敗");
}
刪除操作:
- (void)deleteData: (People *)people
{
// 獲取到上下文對(duì)象
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.managedObjectContext;
[context deleteObject:people];
BOOL isOK = [context save:nil];
NSLog(@"%@",isOK == YES?@"刪除成功":@"刪除失敗");
}
說(shuō)到這里,整個(gè)Core Data框架的入門就結(jié)束了,其實(shí)Core Data還遠(yuǎn)不止這些功能,它還支持自動(dòng)撤銷機(jī)制,一對(duì)多關(guān)聯(lián)等,這里就不一一介紹了