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 makes sense.

If you want to learn more about persistent history tracking, I also recommended watching the WWDC 2017 What’s New in Core Data session in which Apple announces persistent history tracking.

How to Enable Persistent History Tracking

As discussed, we’re going to enable both persistent history tracking and remote notifications. We can do this by setting persistent store options in our NSPersistentStoreDescription, which we use as input for our NSPersistentContainer:

Note that we’ll have to set these options before we instruct the persistent container to load its persistent stores. Otherwise, both options won’t have any effect.

#programming #ios #swift #xcode #mobile

Persistent History Tracking in Core Data
4.90 GEEK