Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-[NSURL initFileURLWithPath:]: nil string parameter' on NSManagedObjectModel

Just trying to get into the Core Data stuff and getting crossed up right off the bat. In my AppDelegate I have the following code:

- (NSManagedObjectModel *)managedObjectModel {

    if (managedObjectModel_ != nil) {
        return managedObjectModel_;
    }
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"DataModel" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
    managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
    return managedObjectModel_;
}

Where @"DataModel" is the name of my .xcdatamodel file - is this correct?

like image 365
Slee Avatar asked Jul 10 '10 23:07

Slee


2 Answers

Changing "momd" to just "mom" worked for me. Marcus S. Zarra's answer also worked for me once I fixed the syntax to:

managedObjectModel_ = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

although I have no idea what that line does.

Edit: I did some more research and I now know what the above line does and why it works/doesn't work. the above line will search your project for all models and add them to the xcdatamodel. This works if you are not using versioned models. However, if you switch to using versioned models in the future this will import all version of the model so you will get both the old and new together which is NOT what you want. So the solution is to do one of two things. If you want to use a non-versioned model use the following lines to grab the model:

NSString *modelPath = [[NSBundle mainBundle]
    pathForResource:@"DataModel" ofType:@"mom"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

If you want to use a versioned model (recommended) select the model and run Design -> Data Model -> Add Model Version from the menubar to create a versioned model. This will automatically change the extension of your model from xcdatamodel to xcdatamodeld. Once this is done use the following lines:

NSString *modelPath = [[NSBundle mainBundle]
    pathForResource:@"DataModel" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

Notice that the only difference is the ofType parameter changes from @"mom" to @"momd". I hope that this clarifies what is going on for everybody who is trying to understand CoreData.D

like image 139
John Scipione Avatar answered Sep 21 '22 06:09

John Scipione


It is often easier to change this to

managedObjectModel_ = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

Then if it is a mom or momd you will still get the model back.

like image 32
Marcus S. Zarra Avatar answered Sep 22 '22 06:09

Marcus S. Zarra