一.CoreData介紹sql
Core Data是iOS5以後纔出現的一個框架,它提供了對象-關係映射(ORM)的功能,即可以將OC對象轉化成數據,保存在SQLite數據庫文件中,也可以將保存在數據庫中的數據還原成OC對象。在此數據操做期間,咱們不須要編寫任何SQL語句,這個有點相似於著名的Hibernate持久化框架,不過功能確定是沒有Hibernate強大的。簡單地用下圖描述下它的做用:數據庫
左邊是關係模型,即數據庫,數據庫裏面有張person表,person表裏面有id、name、age三個字段,並且有2條記錄;app
右邊是對象模型,能夠看到,有2個OC對象;框架
利用Core Data框架,咱們就能夠輕鬆地將數據庫裏面的2條記錄轉換成2個OC對象,也能夠輕鬆地將2個OC對象保存到數據庫中,變成2條表記錄,並且不用寫一條SQL語句。fetch
接下來看看建立模型文件的過程:
1.選擇模板
this
2.添加實體
3.添加Person的2個基本屬性
4.添加Card的1個基本屬性
5.創建Card和Person的關聯關係atom
右圖中的表示Card中有個Person類型的person屬性,目的就是創建Card跟Person之間的一對一關聯關係(建議補上這一項),在Person中加上Inverse屬性後,你會發現Card中Inverse屬性也自動補上了spa
2.NSManagedObject的工做模式有點相似於NSDictionary對象,經過鍵-值對來存取全部的實體屬性orm
1> setValue:forKey:存儲屬性值(屬性名爲key)
注:黑色表示類名,紅色表示類裏面的一個屬性
開發步驟總結:
1.初始化NSManagedObjectModel對象,加載模型文件,讀取app中的全部實體信息
2.初始化NSPersistentStoreCoordinator對象,添加持久化庫(這裏採起SQLite數據庫)
3.初始化NSManagedObjectContext對象,拿到這個上下文對象操做實體,進行CRUD操做
AppDelegate.m文件 注意這點代碼是在建立工程時(勾選上CoreData後)自動帶上的,不用本身寫,只需注意一下個部分的功能便可,提示:數據庫版本遷移時也在這裏進行,已經用紅色標註,
//採用的是棧同步方式 中間有個臨時存儲器
#pragma mark - Core Data stack
//managedObjectContext 託管上下文(上下都管)對象 能夠進行增,刪,改,查
@synthesize managedObjectContext = _managedObjectContext; //managedObjectModel 管理對象模型 將工程裏的全部模型文件合併(爲了之後方便生成數據庫中的表) // @synthesize managedObjectModel = _managedObjectModel; //持久化存儲協調器 實際操做由它來完成
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator; //NSPersistentStore 持久化存儲對象 //NSManagedObject 管理對象(所謂的 model類 如:student.)
- (NSURL *)applicationDocumentsDirectory { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.----.CoredateDemo" in the application's documents directory.
NSLog(@"%@",[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].lastObject); //在splite中,路徑爲字符串類型 , 在coreData中路徑爲URL
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; } #pragma mark ---獲取管理對象模型
- (NSManagedObjectModel *)managedObjectModel { // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) { return _managedObjectModel; } //管理對象模型文件 //與數據庫文件名要對應
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; } #pragma mark ---獲取持久化存儲協調器
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } // Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; //存儲文件名
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoredateDemo.sqlite"]; NSError *error = nil; NSString *failureReason = @"There was an error creating or loading the application's saved data."; //options 版本遷移時使用
#pragma mark ---NSString * const NSMigratePersistentStoresAutomaticallyOption NSInferMappingModelAutomaticallyOption 兩個方法一塊兒用 支持版本遷移
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:@{ NSMigratePersistentStoresAutomaticallyOption:@YES , NSInferMappingModelAutomaticallyOption:@YES} error:&error]) { // Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary]; dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; dict[NSLocalizedFailureReasonErrorKey] = failureReason; dict[NSUnderlyingErrorKey] = error; error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; } #pragma mark--獲取管理對象上下文
- (NSManagedObjectContext *)managedObjectContext { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (!coordinator) { return nil; } _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; return _managedObjectContext; } #pragma mark - Core Data Saving support
//存儲
- (void)saveContext { NSManagedObjectContext *managedObjectContext = self.managedObjectContext; if (managedObjectContext != nil) { NSError *error = nil; if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } }
這是基本環境的配置,包括Core Date數據庫的創建,以及相關兩個類的創建
ViewController.m
#import "ViewController.h"
#import "AppDelegate.h"
#import "Person.h"
#import "Car.h"
@interface ViewController () //管理對象上下文 負責全部與數據有關的相似於_bd(數據庫鏈接對象)
@property(nonatomic,strong)NSManagedObjectContext *manageObjectContext; @end
@implementation ViewController //懶加載 注意要用self調用
#warning 懶加載要用self.進行調用********懶加載中不能使用self
-(NSManagedObjectContext *)manageObjectContext { //由於管理上下文對象的getter方法 在appdelegate中 因此先要獲取appdelegate對象
if (_manageObjectContext == nil) { //獲取AppDelegate對象
AppDelegate *delegate = [UIApplication sharedApplication].delegate; _manageObjectContext = delegate.managedObjectContext; } return _manageObjectContext; } - (void)viewDidLoad { [super viewDidLoad]; [self addPerson]; // [self removePerson]; // [self update];
[self selectAllPerson]; }
核心代碼區:對於Core Data數據庫的增刪改查.
CoreData數據庫的增添
#pragma mark ---增
//添加一個person對象
-(void)addPerson { //1.實例化一個person對象 ,並讓context準備將person對象添加到數據庫裏面 //注意.在coredata實例化一個對象須要使用實體描述
#warning 懶加載要用self.進行調用********
//第一種方式實例化對象
Person *p1 = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.manageObjectContext];//懶加載要用self.進行調用******** // //第二種方式 建立實體描述對象 // NSEntityDescription *personED = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manageObjectContext]; // //根據實體描述對象建立person]對象 // Person *p1 =[[Person alloc]initWithEntity:personED insertIntoManagedObjectContext:self.manageObjectContext]; //設置p1的屬性信息
p1.name = @"張三"; p1.age = @18; // p1.age = [NSNumber numberWithInteger:18];
p1.phoneNum = @"456560"; p1.headImage = UIImagePNGRepresentation([UIImage imageNamed:@"btn_02"]); //建立一個car對象
Car *car1 = [NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:self.manageObjectContext]; car1.brand = @"保時捷"; car1.price = @123344666; car1.color = @"黃色"; // //將car對象添加到集合中 // NSSet *carSet = [NSSet setWithObjects:car1, nil]; // p1.cars = carSet;
Car *car2 = [NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:self.manageObjectContext]; car2.brand = @"寶馬X7"; car2.price = @123344666; car2.color = @"紅色"; //將car對象添加到集合中
NSSet *carSet = [NSSet setWithObjects:car1,car2, nil]; p1.cars = carSet; //3.person保存到數據庫中
BOOL flag = [_manageObjectContext save:nil]; if (flag) { NSLog(@"插入數據成功"); } else{ NSLog(@"插入數據失敗"); } }
CoreData數據庫的刪除
#pragma mark ---刪
-(void)removePerson { //1.實例化查詢請求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; //2.設置查詢條件 (謂詞條件---篩選)
request.predicate = [NSPredicate predicateWithFormat:@"name = '張三'"]; //3.(由管理對象上下文執行查詢)根據查詢條件執行查詢
NSArray *result = [self.manageObjectContext executeFetchRequest:request error:nil]; //刪除結果
for (Person *person in result) { NSLog(@"%@ %@ %@",person.name,person.age,person.phoneNum); //從數據庫中刪除一條記錄
#warning 刪除語句要記清楚------delete:person [self.manageObjectContext deleteObject:person]; } //5.同步保存數據
if ([_manageObjectContext save:nil]) { NSLog(@"刪除成功"); } else{ NSLog(@"刪除失敗"); } }
CoreData數據庫的更改
#pragma mark ---改
-(void)update { //1.實例化查詢請求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Car"]; //2.設置查詢條件 //拼寫注意,細心
request.predicate = [NSPredicate predicateWithFormat:@"brand CONTAINS '寶馬X7'"]; //3.由管理上下文對象 按照查詢條件執行查詢
NSArray *result = [self.manageObjectContext executeFetchRequest:request error:nil]; for (Car *car in result) { NSLog(@"%@ %@ %@",car.brand,car.price,car.color); //更改車的品牌
car.brand = @"寶馬X5"; } //5.數據同步
if ([_manageObjectContext save:nil]) { NSLog(@"更新成功"); } else{ NSLog(@"更新失敗"); } }
CoreData數據庫的查詢
#pragma mark ---查
-(void)selectAllPerson { //1.實例化查詢請求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; //2.設置排序
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES]; request.sortDescriptors = @[sort]; //3.設置帥選條件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < 20 && name LIKE '*三'"]; request.predicate = predicate; //4.由管理上下文對象 執行查詢對象 執行查詢
NSArray *result = [self.manageObjectContext executeFetchRequest:request error:nil]; for (Person *person in result) { NSLog(@"%@%@%@",person.name,person.age,person.phoneNum); } }