Swift: Core Data Fetching & Sorting Across Multiple Persistent Stores

191 Views Asked by At

I have an application that stores data into two seperate NSPersistentStores. The idea being, Store A is bundled with the application and provides initial data. Store B is used for User Generated data. Both stores share the same Entity.

When performing a fetch request on the Entity with a SortDescriptor, CoreData performs a separate search and sort for each PersistentStore and then combines the result.

For example if I had the following Person Entity data in each store:

Store A

  • Name: "Martin", Age: 50
  • Name: "Bob", Age: 20

Store B

  • Name: "Jennifer", Age: 30
  • Name: "Claire", Age: 10

The result that is returned is as follows:

  • "Bob": Age 20
  • "Martin": Age 50
  • "Claire": Age 10
  • "Jennifer": Age 30

When the result that I'm expecting from the fetch request should be:

  • "Claire": Age 10
  • "Bob": Age 20
  • "Jennifer": Age 30
  • "Martin": Age 50

I can see this clearly in the SQL Query Logs where each store is independently searched and sorted.

CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.Z_OPT, t0.NAME, t0.AGE = ? ORDER BY t0.ZAGE
CoreData: annotation: sql connection fetch time: 0.0003s
CoreData: annotation: total fetch execution time: 0.0005s for 4 rows.
CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.Z_OPT, t0.NAME, t0.AGE = ? ORDER BY t0.ZAGE
CoreData: annotation: sql connection fetch time: 0.0002s
CoreData: annotation: total fetch execution time: 0.0003s for 1 rows.

I know that it is possible to perform a sort on the returned fetched objects which would solve the issue, my concern though is that an NSFetchRequest sort is more performant.

Is there a better way of performing this action, or is this the behavior of CoreData?

1

There are 1 best solutions below

0
Michael Tsai On

I suggest posting more about how you are doing the fetch because this should work. Core Data should be doing a separate SELECT for each store, but then it should merge the results together so that the fetched objects are sorted.

The exception is if you have limited the fetched properties to not include the sort keys, because then it will not have the information that it needs to maintain the sort when merging.