Houman
Houman

Reputation: 66320

Coredata: Multiple xcdatamodeld files in the same iOS project?

Is it possible to serve two xcdatamodeld core data in the same project and load each according to a conditional?

I have BTPModel.xcdatamodeld and FTModel.xcdatamodeld

According to the comments this line below does this:

NSManagedObjectModel model = [NSManagedObjectModel mergedModelFromBundles:nil];

// looks up all models in the specified bundles and merges them; if nil is specified as argument, uses the main bundle

Can I do something like this? (pseudo code)

if (config == @"FT") {
   model = [NSManagedObjectModel load:@"FTModel.xcdatamodeld"];  
} else {
   model = [NSManagedObjectModel load:@"BPTModel.xcdatamodeld"];  
}

UPDATE:

I have now tried this

        NSURL *url = [[NSBundle mainBundle] URLForResource:@"F11iModel" withExtension:@"xcdatamodeld"];

Without any luck. url remains null.

UPDATE Extension is momd. Now it works!

        NSURL *url = [[NSBundle mainBundle] URLForResource:@"F11iModel" withExtension:@"momd"];

Upvotes: 4

Views: 1353

Answers (1)

Mundi
Mundi

Reputation: 80265

Of course you can. Just a few things to pay attention to:

The loading of a specific model is not done with some load method, but with initWithContentsOfURL. You get the URL with the main bundle's URLForResource. You can pass different resource names to this according to the configuration information.

I would recommend that you also use different persistent stores to make sure there is no attempt to open a the store with the wrong model (which will crash your app).

Upvotes: 1

Related Questions