核心数据版本控制(轻量级迁移)问题

时间:2015-01-28 14:04:01

标签: ios objective-c iphone core-data

我在我的应用程序中使用核心数据,其第一个版本于10月发布。然后我在数据模型中做了一些更改并上传了下一个版本。它开始在现有用户的设备上崩溃(在启动时崩溃),但它在重新安装或新用户下载时正常运行。 然后我学习了版本控制并创建了一个新版本,即1.1并在app delegate中添加了以下代码行

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"golfCourse.sqlite"];

NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

NSDictionary *options = @{
                          NSMigratePersistentStoresAutomaticallyOption : @YES,
                          NSInferMappingModelAutomaticallyOption : @YES
                          };

if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

     Typical reasons for an error here include:
     * The persistent store is not accessible;
     * The schema for the persistent store is incompatible with current managed object model.
     Check the error message to determine what the actual problem was.


     If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

     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.

     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

    abort();
}

return _persistentStoreCoordinator;}

我在模拟器和iphone上测试了它并且它工作正常,但是当我上传它。对于现有应用用户,它在启动时再次崩溃。

iTunes上没有崩溃日志。

为了测试这个问题,我创建了另一个版本的数据模型并遵循了这一点 approach测试模型版本。 它运作正常。 应用程序在启动时崩溃,所以我猜数据模型的变化是原因。但我不确定为什么在添加适当的选项(轻量级迁移)后它会崩溃。

1 个答案:

答案 0 :(得分:0)

您是否有反映更改的新版本模型?或者您刚刚在一个独特的xcdatamodeld文件中完成了更改? 要创建新的模型版本:

  1. 选择您的xcdatamodel文件
  2. 编辑 - >添加模型版本
  3. 再次选择您的xcdatamodel文件,然后在右侧面板中找到Model版本并将当前设置为您刚刚创建的模型
  4. 检查https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmModelFormat.html#//apple_ref/doc/uid/TP40004399-CH3-SW1