CoreData
是一門功能強大的數據持久化技術,位於SQLite數據庫之上,它避免了SQL的複雜性,能讓咱們以更天然的方式與數據庫進行交互。CoreData提供數據--OC對象映射關係來實現數據與對象管理,這樣無需任何SQL語句就能操做他們。CoreData
數據持久化框架是Cocoa API
的一部分,⾸次在iOS5 版本的系統中出現,它容許按照實體
-屬性
-值模型
組織數據,並以XML
、⼆進制文件
或者SQLite數據⽂件
的格式持久化數據.sql
SQLite數據庫
1、基於C接口,須要使用SQL語句,代碼繁瑣 2、在處理大量數據時,表關係更直觀 3、在OC中不是可視化,不易理解
CoreData數據結構
1、可視化,且具備undo/redo能力 2、能夠實現多種文件格式: * NSSQLiteStoreType * NSBinaryStoreType * NSInMemoryStoreType * NSXMLStoreTyp 3、蘋果官方API支持,與iOS結合更緊密
NSManagedObjectContext
(數據上下文)app
NSPersistentStoreCoordinator
(持久化存儲助理)框架
NSManagedObjectModel
(數據模型)編輯器
NSManagedObject
(被管理的數據記錄)fetch
NSEntityDescription
(實體結構)atom
NSFetchRequest
(數據請求)spa
後綴爲.xcdatamodeld
的包3d
各種之間關係圖
依賴關係
.項目添加CoreData
圖1.
圖2.
圖3.
圖4.
圖5.
此消息是提示項目是OC項目,可是生成model實體類是使用Swift語言,須要創建橋接,通常採用辦法是使用在上圖3中把Swift修改成Objective-C.
生成實體類後編譯可能會有此錯誤:
選中表實體修改屬性codegen爲Manual/None,默認是Class Definition
作完以上步驟後保證項目正常編譯Success後繼續下面操做.
@interface ViewController () @property (nonatomic, strong) NSManagedObjectContext *context; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //一、建立模型對象 //獲取模型路徑 NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Company" withExtension:@"momd"]; //根據模型文件建立模型對象 NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; //二、建立持久化助理 //利用模型對象建立助理對象 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; //數據庫的名稱和路徑 NSString *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlPath = [docStr stringByAppendingPathComponent:@"mySqlite.sqlite"]; NSLog(@"path = %@", sqlPath); NSURL *sqlUrl = [NSURL fileURLWithPath:sqlPath]; //設置數據庫相關信息 [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:nil]; //三、建立上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; //關聯持久化助理 [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進行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];
查詢記錄:
//查詢數據 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(@"數據查詢錯誤%@",error); }else{ //結果集 // 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 執行的sql
經過如下方式能夠打開控制檯sql輸入,進入項目Edit Scheme
添加2個參數 1. 輸入"-com.apple.CoreData.SQLDebug" 2.添加"1"
輸入後從新運行項目,就能夠看到控制檯sql輸出信息.