lundi 10 décembre 2012

Embedding a Core Data model from a static library project

In one of my project, I want to share a Core Data model between 2 projects. I have a common static library project where the model and classes are defined.

Situation


  • a common project that builds a static library which contains my Core Data model (to be shared with an iOS and an OSX project)
  • my main iOS project

Problem

  • static library cannot include resources
  • how can I give make my main project use the Core Data model ?

Solution

  • Create a new target of type Bundle (in OSX/Frameworks and Library)
  • Change the build settings of this target:
    • Base SDK:  Latest iOS 
    • Supported platform: iOS
    • Valid architecture: arm architecture
  • Add your model file (.xcdatamodeld) to the Build phases / Compile Sources section of the bundle target
  • Link your bundle with Core Data (add it to Build phase / Link Binary section)
  • Build the bundle target
Now in your main project:
  • Select the project to show Build Phases / Copy Bundle Resources
  • Drag the Bundle target product (from Products group in the project navigator) to the Copy Bundle Resources section
  • If it s not already there, add your static library: in Build Phases / Link binary section, use the "+" button to add your static library file
  • Load the model from the bundle:
NSString *staticLibraryBundlePath = [[NSBundle mainBundle] pathForResource:@"ModelBundle" ofType:@"bundle"];

NSURL *staticLibraryMOMURL = [[NSBundle bundleWithPath:staticLibraryBundlePath] URLForResource:@"MyDataModel" withExtension:@"momd"];

model = [[NSManagedObjectModel alloc] initWithContentsOfURL:staticLibraryMOMURL];

Aucun commentaire: