__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/
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With