managedObjectModel is nil (Cannot create an NSPersistentStoreCoordinator with a nil model)

那年仲夏 提交于 2019-12-22 15:25:12

问题


I have this special case scenario, where in my app works perfectly fine for some time and crashes inconsistently after some time. The error that i get during the crash is "Cannot create an NSPersistentStoreCoordinator with a nil model".

I tried debugging my app and found that the managedObjectModel is returning NULL sometimes. To add fuel to the fire, this scenario is not at all consistent. For some time the managedObjectModel is fine. But, suddenly it returns NULL...

Here is the code that I am using to create a managed object model.

- (NSManagedObjectModel *)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];

    NSLog(@"managedObjectModel_ %@", [managedObjectModel_ entities]);

    return managedObjectModel_;
}

As you can see above, due to some special requirements, I have placed my .xcdataModeld file in a separate bundle and referencing it from there. I got struck and need some help.... Thanks


回答1:


First of all, make sure you never reset managedObjectModel_ to nil. Just search your source code for "managedObjectModel_ =", the only result should be in the managedObjectModel code you posted.

Secondly, make sure that managedObjectModel_ is either inaccessible from outside or (if you expose managedObjectModel as a property) readonly.

Thirdly, make sure there's one and only one instance of the class managing the Core Data stack. If it's the UIApplication delegate initialized in the main window nib, you shouldn't create it programmatically. If it's a singleton, check if there's really a single instance of it.

When you are absolutely sure everything is right, it's time to go digging deeper. You can try setting a watchpoint in GDB to managedObjectModel_.

The worst thing possibly going on in your code is a kind of memset/memmove operations which happen to overwrite memory occupied by your Core Data stack manager. But this sort of error is too random to always hit a given memory address, so I wouldn't count on it.



来源:https://stackoverflow.com/questions/9212313/managedobjectmodel-is-nil-cannot-create-an-nspersistentstorecoordinator-with-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!