Member-only story
Persistent History Tracking in Core Data
Understanding how persistent history tracking works
WWDC 2017 introduced a new concept available from iOS 11: persistent history tracking. It’s Apple’s answer for merging changes that come from several targets like app extensions. Whenever you change something in your Core Data database from your Share Extension, a transaction is written that can be merged into any of your other targets.
You might have read my article Core Data and App extensions: Sharing a single database that suggests Darwin notifications share a database between app extensions. This has been a great solution and still works, but it isn’t recommended as a solution by Apple and uses undocumented Darwin notifications. Therefore, I would highly recommend switching over to persistent history tracking if you’ve used Darwin notifications up until today.
How Does Persistent History Tracking Work?
With persistent history tracking enabled, your app will start writing transactions for any changes that occur in your Core Data store. Whether they happen from an app extension, background context, or your main app, they’re all written into transactions.
Each of your app’s targets can fetch transactions that happened since a given date and merge those into their local store. This way, you can keep your store up to date with changes from other coordinators. After you’ve merged all transactions, you can update the merged date so you’ll only fetch new transactions on the next merge.
Remote Change Notifications
Although it was introduced in iOS 11, it’s best to implement this feature using remote change notifications, which were introduced in iOS 13. This allows you to only fetch new transactions when a remote change occurred. Up until this new feature was introduced, we had to do a poll for changes whenever that fit (e.g. during a didBecomeActive
event). Fetching for transactions is expensive, so it's much better to do this when there's actually a new transaction to fetch.
In this article, you’ll see several performance improvements to narrow down the amount of work that needs to be done. Only relevant transactions are fetched — and only when it…