检测轻量级核心数据迁移 [英] Detecting a Lightweight Core Data Migration
问题描述
我正在使用Core Data的自动轻量级迁移。但是,当一个特定的实体在迁移过程中创建时,我想填充一些数据。当然,我可以检查实体是否每次应用程序启动时是空的,但是当Core Data有一个迁移框架时,这似乎是低效的。
I'm using Core Data's automatic lightweight migration successfully. However, when a particular entity gets created during a migration, I'd like to populate it with some data. Of course I could check if the entity is empty every time the application starts, but this seems inefficient when Core Data has a migration framework.
我已经尝试使用 NSPersistentStoreCoordinatorStoresDidChangeNotification $(可能使用KVO或通知)
I've tried using the NSPersistentStoreCoordinatorStoresDidChangeNotification
, but it doesn't fire when migrations occur.
推荐答案
要检测是否需要迁移,请检查查看持久存储协调器的受管对象模型是否与现有存储的元数据兼容(根据Apple的需要移转):
To detect whether a migration is needed, check to see if the persistent store coordinator's managed object model is compatible with the existing store's metadata (adapted from Apple's 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);
如果 pscCompatibile
是 NO
,则需要进行迁移。要检查实体更改,请将源元数据
字典中的 NSStoreModelVersionHashes
键与 [destinationModel实体]
:
If pscCompatibile
is NO
, then a migration will need to occur. To examine the entity changes, compare the NSStoreModelVersionHashes
key in the sourceMetadata
dictionary to the [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);
这篇关于检测轻量级核心数据迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!