simplexity simplexity - 1 year ago 67
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,

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

I query a web database that pushes updates since the highest
, 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,
, 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 Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download