25

Core Data の自動軽量移行を正常に使用しています。ただし、移行中に特定のエンティティが作成された場合は、それにデータを入力したいと思います。もちろん、アプリケーションが起動するたびにエンティティが空かどうかを確認することもできますが、Core Data に移行フレームワークがある場合、これは効率が悪いようです。

軽量の移行がいつ発生するか (おそらく KVO または通知を使用して) を検出することは可能ですか?それとも標準的な移行を実装する必要がありますか?

を使用してみましたNSPersistentStoreCoordinatorStoresDidChangeNotificationが、移行が発生したときに起動しません。

4

3 に答える 3

61

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

の場合pscCompatibileNO、移行を行う必要があります。エンティティの変更を調べるには、ディクショナリの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);
于 2010-06-12T19:14:56.533 に答える
1

そのエンティティの NSManagedObject をサブクラス化し、-awakeFromInsert: をオーバーライドするのはどうですか? それとも、アプリの他の部分でこのエンティティを作成していますか?

于 2010-09-21T08:28:18.607 に答える