Retrieve Core Data Entities in Order of Insertion
Asked Answered
M

3

6

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.

Magistrate answered 25/4, 2010 at 10:46 Comment(0)
P
8

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.

Petta answered 25/4, 2010 at 16:44 Comment(1)
setting the default value to NOW won't work, you will need to put self.date = [NSDate date]; inside -(void)awakeFromInsert in your NSManagedObject subclass.Catapult
A
3

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.

Ameeameer answered 18/12, 2015 at 18:59 Comment(1)
I know this is old, but I'm looking at doing something very similar. Are there any performance issues with this, having to rewrite potentially thousands of records every time something is moved?Olpe
A
0

Inside the "NSFetchedResultsController" there is a sortDescriptor

let sortDescriptor = NSSortDescriptor(key: "dateSort", ascending: false)

Create an "entity". When adding to the context, I fill in the date. "Date()"

Arcane answered 12/2, 2023 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.