移行が必要かどうかを検出するには、永続ストア コーディネーターの管理対象オブジェクト モデルが既存のストアのメタデータと互換性があるかどうかを確認します (Apple の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
キーを次のキーと比較します。sourceMetadata
[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);