Core Data
- Core Data框架提供了對象-關(guān)系映射(ORM)的功能,即能夠?qū)C對象轉(zhuǎn)化成數(shù)據(jù),保存在SQLite3數(shù)據(jù)庫文件中,也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成OC對象。在此數(shù)據(jù)操作期間,不需要編寫任何SQL語句。使用此功能,要添加CoreData.framework和導入主頭文件<CoreData/CoreData.h>
模型文件
在Core Data,需要進行映射的對象稱為實體(entity),而且需要使用Core Data的模型文件來描述應用的所有實體和實體屬性
-
這里以Person和Card(身份證)2個實體為例子,先看看實體屬性和之間的關(guān)聯(lián)關(guān)系
- Person中有個Card屬性,Card中有個Person屬性
- 屬于一對一雙向關(guān)聯(lián)
-
創(chuàng)建文件
- Core Data - > Data Model
-
添加實體
- Add Entity
-
添加Person實體的基本屬性
- Attributes - > 加號 - > 不勾選 Translent
添加Card實體的基本屬性 等等
NSManagedObject
- 通過Core Data從數(shù)據(jù)庫取出的對象,默認情況下都是NSManagedObject對象
- NSManagedObject的工作模式有點類似于NSDictionary對象,通過鍵值對來存取所有的實體屬性
- setValue:forKey: 存儲屬性值(屬性名為key)
- valueForKey: 獲取屬性值(屬性名為key)
搭建Core Data上下文環(huán)境
- 從應用程序包中加載模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
- 傳入模型,初始化NSPersistentStoreCoordinator
NSPersistentStoreCoordinator *psc = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model] autorelease];
- 構(gòu)建SQLite文件路徑
NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.data"]];
- 添加持久化存儲庫,這里使用SQLite作為存儲庫
NSError *error = nil;
NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
if (store == nil) { // 直接拋異常
[NSException raise:@"添加數(shù)據(jù)庫錯誤" format:@"%@", [error localizedDescription]];
}
- 初始化上下文,設置persistentStoreCoordinator屬性
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
context.persistentStoreCoordinator = psc;
// 用完之后,還是要[context release];
添加數(shù)據(jù)
- 傳入上下文,創(chuàng)建一個Person實體對象
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
[person setValue:@"MJ" forKey:@"name"];
[person setValue:[NSNumber numberWithInt:27] forKey:@"age"];
- 傳入上下文,創(chuàng)建一個Card實體對象
cription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:context];
[card setValue:@"4414241933432" forKey:@"no"];
- 設置Person和Card之間的關(guān)聯(lián)關(guān)系
[person setValue:card forKey:@"card"];
- 利用上下文對象,將數(shù)據(jù)同步到持久化存儲庫
NSError *error = nil;
BOOL success = [context save:&error];
if (!success) {
[NSException raise:@"訪問數(shù)據(jù)庫錯誤" format:@"%@", [error localizedDescription]];
}
// 如果是想做更新操作:只要在更改了實體對象的屬性后調(diào)用[context save:&error],就能將更改的數(shù)據(jù)同步到數(shù)據(jù)庫
查詢數(shù)據(jù)
- 初始化一個查詢請求
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
- 設置要查詢的實體
NSEntityDescription *desc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
- 設置排序(按照age降序)
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sort];
- 設置條件過濾(name like '%Itcast-1%')
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*Itcast-1*"];
request.predicate = predicate;
- 執(zhí)行請求
NSError *error = nil;
NSArray *objs = [context executeFetchRequest:request error:&error];
if (error) {
[NSException raise:@"查詢錯誤" format:@"%@", [error localizedDescription]];
}
- 遍歷數(shù)據(jù)
for (NSManagedObject *obj in objs) {
NSLog(@"name=%@", [obj valueForKey:@"name"]
}
刪除數(shù)據(jù)
- 傳入需要刪除的實體對象
[context deleteObject:managedObject];
- 將結(jié)果同步到數(shù)據(jù)庫
NSError *error = nil;
[context save:&error];
if (error) {
[NSException raise:@"刪除錯誤" format:@"%@", [error localizedDescription]];
}
- 打開Core Data的SQL日志輸出開關(guān)
- 1.打開Product,點擊Edit Scheme...
- 2.點擊Arguments,在Arguments Passed On Launch中添加2項
-com.apple.CoreData.SQLDebug
Core Data的延遲加載
- Core Data不會根據(jù)實體中的關(guān)聯(lián)關(guān)系立即獲取相應的關(guān)聯(lián)對象
- 比如通過Core Data取出Person實體時,并不會立即查詢相關(guān)聯(lián)的Card實體;當應用真的需要使用Card時,才會查詢數(shù)據(jù)庫,加載Card實體的信息
創(chuàng)建NSManagedObject的子類
默認情況下,利用Core Data取出的實體都是NSManagedObject類型的,能夠利用鍵-值對來存取數(shù)據(jù)
但是一般情況下,實體在存取數(shù)據(jù)的基礎(chǔ)上,有時還需要添加一些業(yè)務方法來完成一些其他任務,那么就必須創(chuàng)建NSManagedObject的子類
那么生成一個Person實體對象就應該這樣寫
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;