can a dataModel of Coredata be part of any other b

2019-06-07 06:01发布

问题:

I have a datamodel file "Abcde.xcdatamodeld" . It is currently a part of my main bundle and I am referencing it by using the following code.

- (NSManagedObjectModel *)managedObjectModel  {
if (managedObjectModel_ != nil) {
    return managedObjectModel_;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"Abcde" ofType:@"momd"];

NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return managedObjectModel_;
}

Now I have a requirement where in the "Abcde.xcdatamodeld" should be made to be a part of a diffrent bundle and it should be referenced from the new bundle. `

if (managedObjectModel_ != nil) {
    return managedObjectModel_;
}
NSBundle *dataModelBundle = [NSBundle bundleWithIdentifier:@"com.product.dataModelBundle"];
NSString *modelPath = [dataModelBundle pathForResource:@"Abcde" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

return managedObjectModel_;
}

But I am experiencing a crash while running the above code.. MY questions are;

  1. Can a datamodel class be part of any other bundle than the main bundle.
  2. If yes, then where am I going wrong here.

回答1:

Yes you can, I don't know where the included bundle come from. If it is included from an xcode project within another project you have to make sure that your bundle is included in the main bundle. Have a look at this: How to include a bundle in main project xcode 4

For a quick check you can take a look at your application bundle with "Show package content" and see if the included bundle is there. Then, starting from there you have to look for the bundle containing your data model. This is what I did in a project of mine. The hardest part was to include the external bundle. I think you are almost there with your code.

NSBundle *bundle = [NSBundle mainBundle];    
NSString *includedModelPath = [bundle pathForResource:@"YourIncludedBundle" ofType:@"bundle"];
NSURL *includedModelURL = [[NSBundle bundleWithPath:includedModelPath] URLForResource:@"DataModel" withExtension:@"momd"];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSURL *storeUrl = [NSURL fileURLWithPath: [documentsDirectory stringByAppendingPathComponent: dbname]];
self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:includedModelURL];

I have just copied and paste from my code, and make it more verbose to explain better.