有没有一种方法可以按添加对象的时间顺序对核心数据进行排序?

问题描述:

如果我只是将模拟的data添加到coreData中,如下所示:

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)"
        }
    }

但是当我fetch data时,它不是按1、2、3顺序排列的,而是随机列出的.有没有一种方法可以完全按照storecoreData的顺序来storefetch data?这很重要,因为我希望能够通过将cells的顺序拖到另一个位置,然后将更改存储到coreDatabase来重新排列.

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. NSManagedObject子类中添加一个属性(当然也在模型中)

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

@NSManaged var itemAdded : Date

  • 覆盖awakeFromInsert

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

  • 现在您可以按itemAdded