2

I'm currently working on encrypting Core Data stores.

The end goal is to have a store with FileProtectionType.Complete for maximum protection, but there are some tasks that may finish in the background, meaning protected data isn't available, so it can't be saved to the main store.

My current process is, when protected data isn't available, to save the changes to a secondary store with FileProtectionType.completeUnlessOpen.

Then, when protected data becomes available again (func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication)), merging the secondary store back in to the primary store.

This seems to work to some degree, but not as I'd hoped.

For example:

In the primary store, I create a User and set the first and last name fields.

In the background, after protected data has become unavailable, I update the first and last name fields. Because protected data isn't available, this gets saved to the secondary store.

When protected data becomes available again, I merge the two store together using the following:

secondaryStoreCoordinator.migratePersistentStore(secondaryStore, to: primaryStoreURL, options: primaryOptions, withType: NSSQLiteStoreType)

This then seems to create a new User in the primary store, rather than doing as I'd hoped and updating the existing User.

So my questions are two-fold:

1) Is this the best way to handle the scenario I have explained?

2) How would I go about making the migration update the existing User rather than creating a new one? Would it be a case of creating a custom MigrationManager?

I have looked at countless other StackOverflow questions to help me get to the point I'm at now where the two stores are used at the correct time, and merged together to the current level including, but not restricted to, the following:

What is an efficient way to Merge two iOS Core Data Persistent Stores?

Encryption with Core Data in background

https://developer.apple.com/documentation/foundation/nsfileprotectiontype?language=objc

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/Introduction.html#//apple_ref/doc/uid/TP40004399-CH1-SW1

Matthew Hallatt
  • 1,310
  • 12
  • 24
  • 2
    How does Core Data recognise the same objects to merge data together? I have a feeling that with something like this it will be more like a "sync" than a "merge". You may have to access your secondary store and get the entities out one-by-one to write into the primary store. – Fogmeister Jul 03 '17 at 09:43

0 Answers0