Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: model is nil while modelURL is valid

__managedObjectModel is nil even modelURL exists. There is a similar post, but the accepted answer (rename model file and relaunch Xcode) doesn't work for me.

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

    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return __managedObjectModel;
}

I po modelURL in console

(lldb) po modelURL
(NSURL *) $4 = 0x088832f0 file://localhost/Users/philip/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/9E59167C-8D9E-4ADE-BBD7-0BE9A33A6A86/Failed.app/Failed.momd/
like image 536
Philip007 Avatar asked Feb 20 '23 12:02

Philip007


1 Answers

I solved the problem after 3 hours..finally. The solution is simple though: just use the following code

__managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

instead of

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Failed" withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

The reason is that I once created new model file (.xcodemodeld) and delete the old one. And the two model files have different names. In fact, the old model file is NOT deleted at all. It's still inside the app main bundle.

I check the iphone simulator directory and surprisingly see two compiled model files (.momd) are both there! I tried to delete the old momd. But every time my app gets running, the old momd appears again. I go check target build phase and make sure the old model file isn't in compile sources. So weird..

Since multiple compiled model files exist in main bundle, they need to be merged. That's why mergedModelFromBundles: comes into play instead of a single modelURL.

If you never delete any model file, use single modelURL should be no problem.

Although problem solved, I don't understand why simulator keeps all deleted model files in the main bundle. It doesn't make sense to me. Anyone would explain?

like image 133
Philip007 Avatar answered Mar 03 '23 23:03

Philip007