本篇主要講述一些細枝末節的知識點。
在 Xcode 中,建模時就可以添加屬性並標識實體間的相互關系,具體如下圖及說明:
創建 NSManagedObject 子類的好處是可以獲得類型校驗,不必使用如下沒有類型校驗的代碼:
NSManagedObject *event = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
[event setValue:[NSDate date] forKey:@"creationDate"];
步驟:
fetch data 時可以直接使用 code snippet:
使用斷言(Predicate)
斷言可以用來篩選取出的數據,代碼如下(同樣可用 code snippet):
-(void)loadData
{
// 創建請求
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// 設置排序描述
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
// 創建斷言(示例)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"description BEGINSWITH 'TOM' AND createDate < %@", [NSDate date]];
[request setPredicate:predicate];
// 執行請求
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
NSLog(@"error loading data");
}
[self setEventsArray:mutableFetchResults];
}
斷言支持多種寫法,例如 ==(相等)、LIKE(模糊匹配,配合 * 通配符)、BEGINSWITH(前綴匹配)、日期比較,以及 AND 組合條件等;配合 [c]、[cd] 還可實現忽略大小寫的匹配。
創建模板的好處是 Xcode 本身提供了一個編輯器,無需自己編寫斷言代碼,可用圖形化方式編輯條件,也便於管理:
// 創建 Fetch Request
NSFetchRequest *fetchRequest = [[self managedObjectModel] fetchRequestTemplateForName:@"EssentialCourses"];
// 創建排序描述
NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:@"releaseDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sort, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(@"Problem! %@",error);
}
for (Course *c in fetchedObjects) {
NSLog(@"Course: %@ by author: %@", c.title, c.author);
}
數據不能兼容
對於數據不能兼容的情況,我們在 AppDelegate 中做如下處理:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataCourse.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// 刪除記錄
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
注意其中的 removeItemAtURL——當存儲無法添加時,直接刪除舊的數據庫文件。
向前兼容
為了讓數據能夠向前兼容老版本,你需要做如下工作:
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
這裡描述的還是簡單情況,實際的版本管理和數據合併更為複雜,可能需要參考蘋果官方文檔 Core Data Versioning 相關章節。
到這裡,Core Data 相關功能基本介紹完畢。整體看來,Core Data 的學習曲線頗為陡峭,但基本使用其實很簡單,建議大家在工作中逐步摸索。文末附上作者學習用的完整小例子下載地址,供大家參考。