Retrieve Core Data Entities in Order of Insertion

主宰稳场 提交于 2019-12-03 08:42:53

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.

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"

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!