CoreData簡介
CoreData是一門功能強(qiáng)大的數(shù)據(jù)持久化技術(shù),位于SQLite數(shù)據(jù)庫之上,它避免了SQL的復(fù)雜性,能讓我們以更自然的方式與數(shù)據(jù)庫進(jìn)行交互。CoreData提供數(shù)據(jù)--OC對象映射關(guān)系來實(shí)現(xiàn)數(shù)據(jù)與對象管理,這樣無需任何SQL語句就能操作他們。CoreData數(shù)據(jù)持久化框架是Cocoa API的一部分,?次在iOS5 版本的系統(tǒng)中出現(xiàn),它允許按照實(shí)體-屬性-值模型組織數(shù)據(jù),并以XML、?進(jìn)制文件或者SQLite數(shù)據(jù)?件的格式持久化數(shù)據(jù).
CoreData與SQLite進(jìn)行對比
SQLite
1、基于C接口,需要使用SQL語句,代碼繁瑣 2、在處理大量數(shù)據(jù)時,表關(guān)系更直觀 3、在OC中不是可視化,不易理解
CoreData
1、可視化,且具有undo/redo能力 2、可以實(shí)現(xiàn)多種文件格式: * NSSQLiteStoreType * NSBinaryStoreType * NSInMemoryStoreType * NSXMLStoreTyp 3、蘋果官方API支持,與iOS結(jié)合更緊密
CoreData核心類與結(jié)構(gòu)
NSManagedObjectContext(數(shù)據(jù)上下文)
- 對象管理上下文,負(fù)責(zé)數(shù)據(jù)的實(shí)際操作(重要)
- 作用:插入數(shù)據(jù),查詢數(shù)據(jù),刪除數(shù)據(jù),更新數(shù)據(jù)
NSPersistentStoreCoordinator(持久化存儲助理)
- 相當(dāng)于數(shù)據(jù)庫的連接器
- 作用:設(shè)置數(shù)據(jù)存儲的名字,位置,存儲方式,和存儲時機(jī)
NSManagedObjectModel(數(shù)據(jù)模型)
- 數(shù)據(jù)庫所有表格或數(shù)據(jù)結(jié)構(gòu),包含各實(shí)體的定義信息
- 作用:添加實(shí)體的屬性,建立屬性之間的關(guān)系
- 操作方法:視圖編輯器,或代碼
NSManagedObject(被管理的數(shù)據(jù)記錄)
- 數(shù)據(jù)庫中的表格記錄
NSEntityDescription(實(shí)體結(jié)構(gòu))
- 相當(dāng)于表格結(jié)構(gòu)
NSFetchRequest(數(shù)據(jù)請求)
- 相當(dāng)于查詢語句
后綴為.xcdatamodeld的包
- 里面是.xcdatamodel文件,用數(shù)據(jù)模型編輯器編輯
- 編譯后為.momd或.mom文件
各類之間關(guān)系圖

依賴關(guān)系

基本使用
.項目添加CoreData
圖1.

圖2.
圖3.
創(chuàng)建完實(shí)體Model后,就可以生成實(shí)體類
圖4.

圖5.

此消息是提示項目是OC項目,但是生成model實(shí)體類是使用Swift語言,需要建立橋接,一般采用辦法是使用在上圖3中把Swift修改為Objective-C.
生成實(shí)體類后編譯可能會有此錯誤:


選中表實(shí)體修改屬性codegen為Manual/None,默認(rèn)是Class Definition
做完以上步驟后保證項目正常編譯Success后繼續(xù)下面操作.
創(chuàng)建模型對象和上下文
@interface ViewController () @property (nonatomic, strong) NSManagedObjectContext *context; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1、創(chuàng)建模型對象 //獲取模型路徑 NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Company" withExtension:@"momd"]; //根據(jù)模型文件創(chuàng)建模型對象 NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; //2、創(chuàng)建持久化助理 //利用模型對象創(chuàng)建助理對象 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; //數(shù)據(jù)庫的名稱和路徑 NSString *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlPath = [docStr stringByAppendingPathComponent:@"mySqlite.sqlite"]; NSLog(@"path = %@", sqlPath); NSURL *sqlUrl = [NSURL fileURLWithPath:sqlPath]; //設(shè)置數(shù)據(jù)庫相關(guān)信息 [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:nil]; //3、創(chuàng)建上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; //關(guān)聯(lián)持久化助理 [context setPersistentStoreCoordinator:store]; _context = context; }
保存記錄:
- (IBAction)add:(UIButton *)sender { Employee *employee = [[Employee alloc] initWithContext:self.context]; employee.name = @"張三"; employee.age = 28; employee.rDate = [NSDate date]; Company *company = [[Company alloc] initWithContext:self.context]; company.name = @"A公司"; company.address = @"深圳"; employee.company = company; [self.context save:NULL]; }
使用NSEntityDescription進(jìn)行ManagedObject
NSEntityDescription *employeeDesc = [NSEntityDescription entityForName:NSStringFromClass([Employee class]) inManagedObjectContext:self.context]; Employee *employee = [[Employee alloc] initWithEntity:employeeDesc insertIntoManagedObjectContext:self.context]; employee.name = @"李四"; employee.age = 28; employee.rDate = [NSDate date]; NSEntityDescription *companyDesc = [NSEntityDescription entityForName:NSStringFromClass([Company class]) inManagedObjectContext:self.context]; Company *company = [[Company alloc] initWithEntity:companyDesc insertIntoManagedObjectContext:self.context]; company.name = @"B公司"; company.address = @"香港"; employee.company = company; [self.context save:NULL];
修改記錄:
self.employee.age = 29; [self.context save:NULL];
刪除記錄:
[self.context deleteObject:self.employee];
[self.context save:NULL];
查詢記錄:
//查詢數(shù)據(jù) NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([Employee class]) inManagedObjectContext:self.context]; [fetchRequest setEntity:entity]; // Specify criteria for filtering which objects to fetch //謂詞搜索 // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 28", ]; // [fetchRequest setPredicate:predicate]; // Specify how the fetched objects should be sorted //排序方法(這里為按照年齡升序排列) NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]]; NSError *error = nil; NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error]; if (fetchedObjects == nil) { NSLog(@"數(shù)據(jù)查詢錯誤%@",error); }else{ //結(jié)果集 // for (NSManagedObject *employee in fetchedObjects){ // NSLog(@"%@",[employee valueForKey:@"name"]); // } for (Employee *employee in fetchedObjects){ NSLog(@"%@-%d-%@-%@-%@",employee.name,employee.age,employee.rDate,employee.company.name,employee.company.address); } }
Xcode控制臺顯示CoreData 執(zhí)行的sql
通過以下方式可以打開控制臺sql輸入,進(jìn)入項目Edit Scheme

添加2個參數(shù) 1. 輸入"-com.apple.CoreData.SQLDebug" 2.添加"1"
輸入后重新運(yùn)行項目,就可以看到控制臺sql輸出信息.


浙公網(wǎng)安備 33010602011771號