Coredata的使用方法(簡)
一直以來只知道iOS儲存的四種方法,常用的也是NSUserDefault和Coredata。前者使用自不必說。這裡只對Coredata的簡單用法做個小結。供初學者參考。
本文將通過一個小demo,來展示coredata基本的使用:對資料的儲存,和增刪改查等行為。
首先我們要確定兩個對象的關係
一個family家庭有多個成員member,而一個member只屬於一個家庭。
1.我們首先建立一個項目,勾選Use Core Data選項
2.在.xcdatamodel檔案中,建立兩個實體,Family和Member
3.建立兩個實體之間的聯絡,Type代表兩個實體之間的關係,To Many表示一個family可以對應多個Member對象,而members屬性就是這些Member 對象的集合;
這裡還有一個重要的點就是Delete Rule,DeleteRule的四個選項中:
Deny 可以拒絕刪除請求
Nullify 在刪除對象之前重設逆向關係,當刪除對象family之後,他的下屬成員member仍然在資料庫中獨立存在,只是在資料庫中member對應的family為null。
Cascade 刪除對象及它的所有關係(串聯刪除),當刪除一個family對象時,所有與他關聯的member對象也會同時被刪除
No Action 將保證一個關係所指向的對象不受影響,即使這些對象指向了即將被刪除的項
4.預設情況下,利用Core Data取出的實體都是NSManagedObject類型的,能夠利用鍵-值對來存取資料。但是一般情況下,實體在存取資料的基礎上,有時還需要添加一些業務方法來完成一些其他任務,那麼就必須建立NSManagedObject的子類,
5.在資料庫處理中,對象的基本操作增刪改查都是無可爭議的基礎:
+(void)addNewFamilyWithName:(NSString *)name address:(NSString *)address success:(void (^)())success failure:(void(^)(NSError *error))failure{ AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = appDelegate.managedObjectContext; NSManagedObject *family = [NSEntityDescription insertNewObjectForEntityForName:@"Family" inManagedObjectContext:context]; [family setValue:name forKey:@"name"]; [family setValue:address forKey:@"address"]; NSError *error = nil; BOOL isSuccess = [context save:&error]; if (!isSuccess) { if (failure) { failure(error); } }else{ if (success) { success(); } }}+(void)deleteFamily:(Family *)family success:(void (^)())success failure:(void(^)(NSError *error))failure{ AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = appDelegate.managedObjectContext; [context deleteObject:family]; NSError *error = nil; BOOL isSuccess = [context save:&error]; if (!isSuccess) { if (failure) { failure(error); } }else{ if (success) { success(); } }}+(NSArray *)fetchFamilyLists{ AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = appDelegate.managedObjectContext; // 初始化一個查詢請求 NSFetchRequest *request = [[NSFetchRequest alloc] init]; // 設定要查詢的實體 request.entity = [NSEntityDescription entityForName:@"Family" inManagedObjectContext:context]; // 設定排序(按照age降序) // NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO]; // request.sortDescriptors = [NSArray arrayWithObject:sort]; // 設定條件過濾(搜尋name中包含字串"M"的記錄,注意:設定條件過濾時,資料庫SQL語句中的%要用*來代替,所以%M%應該寫成*M*,更多過濾方法,可以看下一篇轉載文章) // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*M*"]; // request.predicate = predicate; // 執行請求 NSError *error = nil; NSArray *objs = [context executeFetchRequest:request error:&error]; if (error) { [NSException raise:@"查詢錯誤" format:@"%@", [error localizedDescription]]; } // 遍曆資料 for (NSManagedObject *obj in objs) { NSLog(@"name=%@", [obj valueForKey:@"name"]); } return objs;}