sree_iphonedev sree_iphonedev - 3 months ago 15
Objective-C Question

Application crash when accessing Coredata from Custom Framework

I have moved all the business logics to a Custom framework project. As part of that, I have moved the xcdatamodeld also to the framework project. Even though I have moved the core data model to framework project, when I try to access the core data model object from the framework as given below, the app get crash.

- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"IHA" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

return _managedObjectModel;


}

What is happening in the above case is that modelURL is getting as nil. Can anyone suggest me the proper way of using CoreData in a custom framework.

Thanks in advance.

Answer

Since you've moved everything to your framework, your Core Data model is no longer in the main bundle of your app, it's in the framework's bundle.

In order to get that bundle from your framework you can do one of the following

NSBundle *frameworkBundle = [NSBundle bundleForClass:[self class]]; // Only works if the current class is part of your framework
NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:@"com.yourframework.identifier"];

And then

NSURL *modelURL = [frameworkBundle URLForResource:@"IHA" withExtension:@"momd"];