2010-06-11 64 views
19

我正在成功使用Core Data的自動輕量級遷移。但是,在遷移期間創建特定實體時,我想用一些數據填充它。當然,我可以在每次應用程序啓動時檢查實體是否爲空,但是當Core Data具有遷移框架時,這似乎效率低下。檢測輕量級核心數據遷移

是否可以檢測何時發生輕量級遷移(可能使用KVO或通知),還是需要實施標準遷移?

我試過使用NSPersistentStoreCoordinatorStoresDidChangeNotification,但它在遷移發生時不會觸發。

回答

54

要檢測是否需要遷移,請檢查是否持久存儲協調的管理對象模型與現有商店的元數據兼容(改編自蘋果Is Migration Necessary):

NSError *error = nil; 
persistentStoreCoordinator = /* Persistent store coordinator */ ; 
NSURL *storeUrl = /* URL for the source store */ ; 

// Determine if a migration is needed 
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType 
                          URL:storeUrl 
                         error:&error]; 
NSManagedObjectModel *destinationModel = [persistentStoreCoordinator managedObjectModel]; 
BOOL pscCompatibile = [destinationModel isConfiguration:nil compatibleWithStoreMetadata:sourceMetadata]; 
NSLog(@"Migration needed? %d", !pscCompatibile); 

如果pscCompatibileNO,然後需要進行遷移。爲了檢驗實體的變化,在sourceMetadata字典NSStoreModelVersionHashes鍵比較給[destinationModel entities]

NSSet *sourceEntities = [NSSet setWithArray:[(NSDictionary *)[sourceMetadata objectForKey:@"NSStoreModelVersionHashes"] allKeys]]; 
NSSet *destinationEntities = [NSSet setWithArray:[(NSDictionary *)[destinationModel entitiesByName] allKeys]]; 

// Entities that were added 
NSMutableSet *addedEntities = [NSMutableSet setWithSet:destinationEntities]; 
[addedEntities minusSet:sourceEntities]; 

// Entities that were removed 
NSMutableSet *removedEntities = [NSMutableSet setWithSet:sourceEntities]; 
[removedEntities minusSet:destinationEntities]; 

NSLog(@"Added entities: %@\nRemoved entities: %@", addedEntities, removedEntities); 
+1

+1分享您答案的第二部分。 – cocoafan 2012-02-03 14:59:48

+0

@hadronzoo它始終在遷移,因爲我開始申請,不應該只做一次? – 2014-02-13 11:05:59

+0

@AhmedZ。不,它只發生一次 – 2017-02-08 17:37:24

1

什麼繼承NSManagedObject該實體,然後重寫-awakeFromInsert:?或者你是否在你的應用的其他部分創建了這個實體?

相關問題