2012-01-16 161 views
10

我的計劃是刪除舊的核心數據堆棧(在NSManagedObjectModel.momd文件&的NSPersistentStore.sqlite文件),因爲:核心數據遷移:如何刪除核心數據棧?

  • 我沒有與核心數據遷移的經驗。
  • 新的.xcdatamodel模式與舊模式完全不同。
  • 我可以安全地刪除用戶的舊數據,因爲它全部存儲在我們的服務器上,並且新應用程序無論如何都會從我們的服務器下載最新數據。

在這種情況下,是完全缺失着手遷移的最佳方式?

回答

11

是,如果您的應用程序需要訪問Internet無論如何做一個完全有效的事情。否則,用戶可能會留下一個空的數據集(當您發現它與當前模型不兼容時刪除舊數據庫,但無法訪問服務器時無法重新填充它)。

從技術上講,這是一件微不足道的事情。當您設置NSPersistentStoreCoordinator

NSURL *storeURL = ...; 
NSManagedObjectModel *managedObjectModel = ...; 
NSError *error = nil; 
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel]; 

// Check if we already have a persistent store 
if ([[NSFileManager defaultManager] fileExistsAtPath: [storeURL path]]) { 
    NSDictionary *existingPersistentStoreMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType: NSSQLiteStoreType URL: storeURL error: &error]; 
    if (!existingPersistentStoreMetadata) { 
     // Something *really* bad has happened to the persistent store 
     [NSException raise: NSInternalInconsistencyException format: @"Failed to read metadata for persistent store %@: %@", storeURL, error]; 
    } 

    if (![managedObjectModel isConfiguration: nil compatibleWithStoreMetadata: existingPersistentStoreMetadata]) { 
     if (![[NSFileManager defaultManager] removeItemAtURL: storeURL error: &error]) 
      NSLog(@"*** Could not delete persistent store, %@", error); 
    } // else the existing persistent store is compatible with the current model - nice! 
} // else no database file yet 

[_persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType 
              configuration: nil 
                URL: storeURL 
               options: nil 
                error: &error]; 
+0

正在此錯誤SQLite的錯誤代碼:11 ,更新後的初始啓動時'數據庫磁盤映像格式不正確'。但在後續啓動時,sqlite文件被刪除時,它不是問題。但似乎我不能避免這一次的應用程序崩潰。感覺應用程序在更新後立即崩潰是令人失望的。有任何想法嗎 ?? – raw3d 2014-01-31 10:52:43

1

如果您創建一個空白的核心數據的應用程序,你發現在應用程序委託蘋果評論的必要代碼:

If you encounter schema incompatibility errors during development, you can reduce their frequency by:

  • Simply deleting the existing store: [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

  • Performing automatic lightweight migration by passing the following dictionary as the options parameter:@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.