You need to make sure both the model and the persistent store file are available to both the app and the extension.
For the model, moving it to a framework is a good idea since it means there's only one copy of the model file. As long as both the app and the extension link to the framework, it'll be available to both. If you do that, it's probably a good idea to put the code that sets up the Core Data stack in the framework too, since it'll be the same in both cases.
You can of course just include the model in both targets. That will mean you'll have two copies of the file, which wastes space. Probably not a lot of space, though.
For the persistent store, you'll have to set up an app group and use a store file in the group directory. App groups is one of the settings in "capabilities" for the app and extension-- turn it on and create a group name. Then put the persistent store file in the group directory, which you can find using code like
NSURL *groupURL = [[NSFileManager defaultManager]
containerURLForSecurityApplicationGroupIdentifier:
@"GROUP NAME HERE"];
[I cover some of this in more detail at my blog].
If you have existing data, you'll have to move it to the new store file. This would look something like
- Check if the old non-group copy of the data exists
- If it does, set up a Core Data stack using that file. Then use
migratePersistentStore:toURL:options:withType:error:
to move it to the new location. Then remove the old copy.
- If the old version doesn't exist, just set up Core Data with the new copy as usual.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…