无法使用nil模型错误创建NSPersistentStoreCoordinator

A f*_*pha 3 iphone core-data core-data-migration ios xcode4.2

我有一个完美运行的coreData datamodel文件.由于一些特殊要求,我删除了旧的datamodel文件并创建了具有完全相同实体的另一个datamodel文件.目前在实体没有变化,从以前的数据模型.我已将此作为另一个捆绑包的一部分并从该捆绑包中引用它.

用于创建managedObjectModel的代码

   if (managedObjectModel_ != nil) {
    return managedObjectModel_;
}
NSBundle *newBundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"dataBundle" withExtension:@"bundle"]];   
NSString *modelPath = [newBundle pathForResource:@"DataHouse" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

return managedObjectModel_;
Run Code Online (Sandbox Code Playgroud)

该应用程序运行良好,直到一段时间突然(随机)我得到一个错误说

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create an NSPersistentStoreCoordinator with a nil model'
*** First throw call stack:`(0x62e052 0x26a9d0a 0xf6e86d 0x64fd 0x624e 0x381b 0x79c9b 0x65f2d 0x1881e0f 0x1882589 0x186ddfd 0x187c851 0x1827322 0x62fe72 0x160892d 0x1612827 0x1598fa7 0x159aea6 0x163437a 0x16341af 0x602966 0x602407 0x5657c0 0x564db4 0x564ccb 0x2791879 0x279193e 0x17e8a9b 0x28a2 0x2815)`
Run Code Online (Sandbox Code Playgroud)

用于创建持久性存储协调器的代码

 if (persistentStoreCoordinator_ != nil) {
    return persistentStoreCoordinator_;
}

NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"DataHouse.sqlite"]];

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(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}    

return persistentStoreCoordinator_;
Run Code Online (Sandbox Code Playgroud)

此错误发生在随机点,但每次运行应用程序时都非常一致.在这一点上我完全感到困惑和震惊......我在论坛中看到了同样的问题,但我想我的是一个特殊的场景.我很确定每次打印时上面代码片段中提到的modelPath变量都会正常运行.

注意:上面的代码片段不是AppDelegate类的一部分.它们是包含所有Coredata方法的特殊类的一部分

afr*_*ick 6

首先验证managedObjectModel_是否有效,您可以使用调试器或在其上调用方法

NSLog(@"%@", [managedObjectModel_ entities]);
Run Code Online (Sandbox Code Playgroud)

验证您的数据模型是否正常.该调用应显示模型中所有实体的数组.接下来检查您的持久存储路径是否指向正确的位置.试试这个:

NSLog(@"%@", [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"DataHouse.sqlite"]);
Run Code Online (Sandbox Code Playgroud)

最后(我认为需要做的是因为它发生在我身上)转到存储.sqlite文件的磁盘上的位置:

~/Library/Application Support/iPhone Simulator/5.0/Applications/{your app id}/Documents
Run Code Online (Sandbox Code Playgroud)

并删除.sqlite文件,以便Core Data在下次构建时生成新的.