4

__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/
Community
  • 1
  • 1
Philip007
  • 3,190
  • 7
  • 46
  • 71
  • *(unrelated)* double underscored names are [reserved](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – Joe Aug 13 '12 at 21:12
  • The double underbar come with the core data template – Philip007 Aug 13 '12 at 21:15
  • ... I'm not a huge fan of all of the generated code and code examples by Apple. With that said Objective-C is supposed to be a proper subset of `C` and should therefore not be using [Reserved Names](http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html) in templates. – Joe Aug 13 '12 at 21:17
  • What is the name of your file, as it appears in your bundle? – rdelmar Aug 13 '12 at 21:35

1 Answers1

8

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?

Philip007
  • 3,190
  • 7
  • 46
  • 71