Search code examples
iphonecore-datastatic-librariesnsbundle

core data in a static library for the iPhone


I've built a static library that makes heavy use of the Core Data framework. I can successfully use the library in my external project, but ONLY if I include the .xcdatamodel file in the main project. That is less than ideal, since the point of the library was to hide implementation details to the maximum possible.

In a separate question, I was informed that I cannot bundle resources with a library (which makes complete sense to me now).

So is there a way to programatically allow the model to be 'discovered' without having to include the model in the main project?


Solution

  • I also created my own static library that uses Core Data. Besides the static library I have a another bundle target in the project where I have a Copy Bundle Resources item, that copies some images and things like that into the bundle and a Compile Sources build phase, where I am compiling the xcdatamodel.

    The final bundle will contain all the necessary files. In your main project that relies on the static library you have to include that bundle as well. Your main project will now have access to the mom file that is needed to use core data.

    To use core data with the mom from the bundle you have to create a merged managed object model in your code (it might be the main project has some core data model as well):

    
    - (NSManagedObjectModel *) mergedManagedObjectModel 
    {   
        if (!mergedManagedObjectModel) 
        {
            NSMutableSet *allBundles = [[[NSMutableSet alloc] init] autorelease];
            [allBundles addObjectsFromArray: [NSBundle allBundles]];
            [allBundles addObjectsFromArray: [NSBundle allFrameworks]];
    
            mergedManagedObjectModel = [[NSManagedObjectModel mergedModelFromBundles: [allBundles allObjects]] retain];
        }
    
        return mergedManagedObjectModel;
    }
    
    
    

    By just including the bundle you will not have to give out the xcdatamodel, only the compiled mom file needs to be included.