核心数据轻量级迁移问题

3D *_*key 5 iphone

我的应用程序目前在应用程序商店中,我正在使用单个添加的属性更新数据模型.我添加了一个模型版本并将其设置为当前版本.

一切正常但是当我测试在包含数据的旧版本上安装新版本的应用程序时,应用程序无法加载而没有错误消息.它将继续失败(只是在屏幕上短暂闪烁),直到我重新启动设备,或者通过XCode或iTunes再次安装更新的应用程序,然后应用程序运行正常并且数据已正确迁移.

我担心,如果这种情况发生在客户身上,他们会在重新安装之前删除该应用并丢失所有数据.有没有人有任何见解?任何帮助表示赞赏

谢谢,我在App Delegate中使用以下代码进行数据迁移:

- (NSManagedObjectModel *)managedObjectModel {
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    NSString *path = [[NSBundle mainBundle] pathForResource:@"DataStore" ofType:@"momd"];
    NSURL *momURL = [NSURL fileURLWithPath:path];
    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
    return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"DataStore.sqlite"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:storePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"DataStore" ofType:@"sqlite"];
        if (defaultStorePath) {
            [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
        }
     }
     NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
     NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], 
     NSMigratePersistentStoresAutomaticallyOption, 
     [NSNumber numberWithBool:YES], 
     NSInferMappingModelAutomaticallyOption, nil];     
     NSError *error;
     persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
     if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
         // Update to handle the error appropriately.
         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
         exit(-1);  // Fail
    }         
    return persistentStoreCoordinator;
}
Run Code Online (Sandbox Code Playgroud)

小智 1

您确定没有对模型的先前版本进行任何更改吗?此行为听起来像是 Core Data 找不到您在设备上拥有的持久存储的模型。

当您启动包含旧版本持久存储的应用程序时,您应该能够在控制台日志中看到任何核心数据错误。

另外,您是在什么时候添加新属性的?如果您在创建新版本之前添加它,则旧版本和新版本都将具有该属性。检查您的旧模型并确保新属性不存在。