Is there a way to keep the sorting in core data in the time order the objects are added? [duplicate]

柔情痞子 提交于 2020-06-17 09:32:21

问题


If I just add mocked data to coreData like this:

func mockData() {´
    let entity = NSEntityDescription.entity(forEntityName: "LocalDoorCoreDataObject", in: context)

    for i in 1...3 {
        var myEntity = MyCoreDataObject(entity: entity!, insertInto: context)
        myEntity.dName = "MOCKED NAME \(i)"
        }
    }

But when I fetch the data it's not ordered 1, 2, 3, but is rather listed randomly. Is there a way to store and fetch the data exactly in the order you store it to the coreData? This is important since I want to be able to rearrange the order of the cells by dragging them to a different place, then storing the changes to coreDatabase.


回答1:


  1. In the NSManagedObject subclass add an attribute (of course also in the model)

    @NSManaged var itemAdded : Date
    
  2. Override awakeFromInsert

    override func awakeFromInsert() {
        super.awakeFromInsert()
        itemAdded = Date()
    }
    

Now you can sort by itemAdded



来源:https://stackoverflow.com/questions/61955435/is-there-a-way-to-keep-the-sorting-in-core-data-in-the-time-order-the-objects-ar

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