NSManagedObjectModel initWithContentsOfURL returns nil sometimes

I use Core Data and have a situation in a real application where I get some crash reports with the following error:

Cannot create an NSPersistentStoreCoordinator with a nil model 

I found that this sometimes happens in the simulator (as well as in the device) , but it does not execute sequentially , and I have not yet found a correlation with what makes it happen sometimes, and not at another time.

After some debugging, I found that the main reason (in terms of code) is that sometimes the createObjectModel method returns nil. Here is my implementation from AppDelegate:

- (NSManagedObjectModel *)managedObjectModel {
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"AppName" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

From time to time, I’m lucky that the debugger works when a failure occurs, and I confirmed that the above method is being called and the method is executing initWithContentsOfURL:, but returns nil.

- , [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] nil?

+5

All Articles