轻量级核心数据迁移后发生无法识别的选择器

时间:2014-03-27 19:48:02

标签: sqlite core-data migration unrecognized-selector

我在iOS上的Core Data(SQLite)数据库的新添加字段上获得了一个无法识别的选择器。我使用Xcode的Editor菜单添加了一个新的模型版本,然后验证了新版本是当前版本。我还确保修改后的表的.h和.m文件已更新,但我手动完成了(如何为您生成这些文件?)。没什么不寻常的,只是一个字符串类型字段。

问题似乎是轻量级迁移永远不会在尝试引用数据库对象的代码运行时发生。 Tring访问newFieldName给出:

-[MyEntity newFieldName]: unrecognized selector sent to instance 0x852b510
2014-03-27 13:26:21.734 ASSIST for iPad[41682:c07] *** Terminating app due to 
uncaught exception 'NSInvalidArgumentException', reason: '-[MyEntity newFieldName]:
unrecognized  selector sent to instance 0x852b510'

产生上述错误的代码行是下面for循环中的唯一一行:

DataStoreCoreData *dStore = [[DataStoreCoreData alloc] initWithDataItemDescription:did];

for (MyEntity *myEnt in [dStore objects])
     NSString *name = [myEnt newFieldName];    

如上所述,当我检查SQLite数据库时,它没有新的字段,这在错误的情况下是有意义的。所以我也逐步执行了应该执行迁移的代码,它似乎工作正常。成功。它看起来如下:

NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"ASSIST.sqlite"]];

// handle db upgrade
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                         [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

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

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error])
    NSLog(@"\r\n Fail. [error localizedDescription]: %@", [error localizedDescription]);
else
    NSLog(@"\r\n Success");

这是第6版db版本升级。所有这些都是轻量级迁移,没有异常问题。上述代码是否应该强制SQLite数据库反映新架构?我怎么做到这一点,或者这里有其他问题吗?

1 个答案:

答案 0 :(得分:0)

我终于找到了答案。我提供的问题代码只是在对数据库进行最小更改时需要修改的代码的一部分(轻量级迁移)。您还需要在创建对象模型时指定新版本。注意" MyNewVersion"在下面的代码中。您应该更新此参数以反映您创建的新版本,然后选择当前的模型版本:

NSString *path = [[NSBundle mainBundle] pathForResource:@"MyNewVersion" ofType:@"mom" inDirectory:@"ASSIST.momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];   
相关问题