2010-06-11 8 views
19

Tôi đang sử dụng thành công việc di chuyển nhẹ tự động của Dữ liệu lõi. Tuy nhiên, khi một thực thể cụ thể được tạo trong quá trình di chuyển, tôi muốn điền nó với một số dữ liệu. Tất nhiên tôi có thể kiểm tra xem thực thể có trống không khi ứng dụng khởi động, nhưng điều này có vẻ không hiệu quả khi Core Data có khung di trú.Phát hiện di chuyển dữ liệu lõi nhẹ

Có thể phát hiện khi di chuyển nhẹ xảy ra (có thể sử dụng KVO hoặc thông báo) hoặc thực hiện yêu cầu di chuyển tiêu chuẩn không?

Tôi đã thử sử dụng NSPersistentStoreCoordinatorStoresDidChangeNotification nhưng không kích hoạt khi quá trình di chuyển diễn ra.

Trả lời

54

Để phát hiện xem một sự chuyển đổi là cần thiết, kiểm tra xem mô hình đối tượng quản lý các cửa hàng điều phối dai dẳng là tương thích với siêu dữ liệu các cửa hàng hiện có của (chuyển thể từ 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); 

Nếu pscCompatibileNO, sau đó di chuyển sẽ cần phải xảy ra. Để kiểm tra những thay đổi đơn vị, so sánh NSStoreModelVersionHashes then chốt trong từ điển sourceMetadata đến [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 để chia sẻ phần thứ hai của câu trả lời của bạn. – cocoafan

+0

@hadronzoo nó đang di chuyển luôn khi tôi khởi động ứng dụng, không nên 'nó được thực hiện một lần duy nhất? –

+0

@AhmedZ. không nó chỉ xảy ra một lần –

1

gì về subclassing NSManagedObject cho thực thể đó, và sau đó trọng -awakeFromInsert :? Hay bạn đang tạo thực thể này ở các phần khác của ứng dụng?