Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Core Data Entities in Order of Insertion

Is there an internal ID variable or timestamp I can use in a NSSortDescriptor to retrieve Core Data entities in the order they were inserted?

I would rather not have to create such properties if there is a cleaner way, though will obviously do so if there are no other alternatives.

like image 983
Andy Shea Avatar asked Apr 25 '10 10:04

Andy Shea


People also ask

What is NS fetch request?

A description of search criteria used to retrieve data from a persistent store.

What is entity in Coredata?

An entity description describes an entity (which you can think of as a table in a database) in terms of its name, the name of the class used to represent the entity in your application, and what properties (attributes and relationships) it has.

What is entity in Coredata Swift?

An entity describes an object, including its name, attributes, and relationships. Create an entity for each of your app's objects.

How to use Core Data in ios swift?

Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.


2 Answers

No, if you want a sort order for your data, you need to add that to your entities yourself. However you can easily add a NSDate attribute that has a default value of "NOW" so that it will auto-populate.

like image 88
Marcus S. Zarra Avatar answered Dec 08 '22 23:12

Marcus S. Zarra


You can also add an attribute to your entity, name it something like "sortNum", and whenever you fetch your entity you fetch it with a sort descriptor.

Step 1

Add the sort attribute, in this case I named it "displayOrder"

Core Data: add sort order

Step 2

Append or insert the new item to your list.

 let insertAt = 0
 managedContextVar.insert(mngdObjectVar, atIndex: insertAt )

Step 3

Resort everything in that entity and update their sort value.

func updateDisplayOrder() {
    for i in 0..<taskList_Cntxt.count {
        let task = taskList_Cntxt[i]
        task.setValue( i, forKey: "displayOrder" )
    }
}

Then save!

Step 4

Now, next time you do a fetch request, make sure you add in the sort.

   let sortDescriptor = NSSortDescriptor(key: "displayOrder", ascending: true )

That's it!

That should handle your sort fairly well. To be honest, sometimes this code does insert my new items second from the top instead of the top, but 95% of the time this code works great. Regardless, you get the idea and can tweak and improve it.

Good luck.

like image 33
Dave G Avatar answered Dec 08 '22 22:12

Dave G