64
技術社區[雲棲]
Core Data淺談係列之四 : 數據模型的版本變遷
繼上一篇文章末尾提到的,一支隊伍可以添加多名球員,不過一名球員隻能屬於一支隊伍中,這分別對應著Core Data中一對多和一對一的屬性關係:


如上兩圖,是在Team實體裏麵添加了一個players關係,指向Player實體,可以一支球隊關聯多名球員,並且最多隻允許關聯15名球員。
同樣地,也為Player實體添加team關係,指向Team實體:

一名球員隻能關聯一支球隊,並且讓這個關係成雙向的,即一個Player對象屬於某支球隊時,該球隊的players屬性就自動關聯該Player對象。
做完以上對表關係的修改,再次運行程序。
Oops,運行不起來——
2013-01-16 16:56:18.667 cdNBA[18591:c07] Error : The operation couldn’t be completed. (Cocoa error 134100.) 2013-01-16 16:56:18.670 cdNBA[18591:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
這是由於我們剛才做了一番修改,persistentStoreCoordinator無法適應新的數據模型。
當開啟一個新版本時,如果數據模型發生變動,我們需要創建一個新版本使用的數據模型:

並將其設置為當前版本使用的數據模型:


So,我們剛才發生的變動都應該應用在cdNBA 2.xcdatamodel上。
除此之外,還需要在persistentStoreCoordinator添加存儲文件時設置一個選項:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (nil != _persistentStoreCoordinator) { return_persistentStoreCoordinator; } NSString *storeType = NSSQLiteStoreType; NSString *storeName = @"cdNBA.sqlite"; NSError *error = NULL; NSURL *storeURL = [NSURLfileURLWithPath:[[selfapplicationDocumentsDirectory] stringByAppendingPathComponent:storeName]]; NSDictionary *options = [NSDictionarydictionaryWithObjectsAndKeys: [NSNumbernumberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumbernumberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; _persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:self.managedObjectModel]; if (![_persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:nilURL:storeURL options:options error:&error]) { NSLog(@"Error : %@\n", [error localizedDescription]); NSAssert1(YES, @"Failed to create store %@ with NSSQLiteStoreType", [storeURL path]); } return _persistentStoreCoordinator; }
做完上麵的工作,再跑一遍Demo。
Brief Talk About Core Data Series, Part 4 : Versioning of The Data Model
最後更新:2017-04-04 07:03:39