simplexity simplexity - 24 days ago 6
iOS Question

Prepend multiple data to beginning of Core Data (Swift)

Could someone give some guidance on how to prepend newly ingested data to Core Data in the correct index order?

I have Core Data with an attribute,

contentID
. The objects are listed as:
5, 4, 3, 2, 1, 0


I query a web database that pushes updates since the highest
contentID
,
5
, and it returns an array with updates:
7, 6


If you simply append it to Core Data, the order will go:
5, 4, 3, 2, 1, 0, 7, 6


How do you prepend it to the front correctly?

And also how do you prepend it in the correct order so that when you prepend the first new object,
7
, and then prepend the second item, 6, it doesn't go:
6, 7, 5, 4, 3, 2, 1, 0


Hope this makes sense... Thanks!

Answer

In general, you should not concern yourself with the order in which objects are written to or stored in the database. Instead, specify the sort order in which you wish to receive the data when you fetch it from the database.

The sort order for a fetch is determined by the sortDescriptors property of the NSFetchRequest. Each NSSortDescriptor specifies the key to determine the order, and whether the results should be in ascending order (v. descending).

So when you perform a fetch, you should in your case specify:

let sort = NSSortDescriptor(key:"contentID", ascending:false)
fetchRequest.sortDescriptors = [sort]
let fetchedResults = managedObjectContent.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]