Sharing a Core Data stack and data between App and Extension in iOS8 Sharing a Core Data stack and data between App and Extension in iOS8 sqlite sqlite

Sharing a Core Data stack and data between App and Extension in iOS8


As @CL notes, SQLite is fine with this. But you're not using SQLite directly, so you may need to do some Core Data-level work to maintain consistency. With an iOS app and an extension, you have two separate processes that can make changes to the data. Your code needs to account for this.

If your app extension only displays data (for example, a "today" extension that only displays data created in the app), you probably don't need to do anything special. If your app is running in the background and creating new data while the extension is visible, it's possible that the extension's data could be slightly out of date. If that's important, you can refresh it. But today extensions typically aren't visible for very long, so it's probably not worthwhile. In this case I'd use NSReadOnlyPersistentStoreOption when setting up the extension's Core Data stack just to be clear about the intention and prevent inadvertent changes.

If your app extension creates new data or modifies existing data, your app needs to be aware of this and respond appropriately. What changes you would make will depend on how exactly the extension handles the shared data. For modified data, your app probably needs to call refreshObject:mergeChanges: on any in-memory managed objects with NO as the second argument. It also probably needs to redo any fetches where the changes might affect a search predicate. That'll ensure you're getting the most recent updates. For new data you would need to re-fetch any data the app is working with to get new additions/deletions. A good time to check would be when the application comes to the foreground (i.e. when UIApplicationWillEnterForegroundNotification is posted).