简体   繁体   English

如何使用Swift3访问CoreData中的数据索引

[英]How to access data index in CoreData using Swift3

I saved datas in entity of CoreData. 我在CoreData.实体中保存了数据CoreData. Also I can access data in CoreData through object.value(forKey:"attribute") . 我也可以通过object.value(forKey:"attribute")访问CoreData中的数据。 But, I don't know how to access data using index. 但是,我不知道如何使用索引访问数据。

follow code is my access way 遵循代码是我的访问方式

    let context = getContext()
    let fetchRequest : NSFetchRequest<Entity> = Entity.fetchRequest()
    let result = try? context.fetch(fetchRequest){
       for object in result
       object.value(forKey:"attribute")...
       ...
       }
    }

How to access data in CoreData using index of data? 如何使用数据索引访问CoreData中的数据?

Your result is type of Array so you can access the object from result like result[0] and so on. 您的结果是Array类型,因此您可以从result[0]result[0]访问该对象。

if index < result.count {
    let obj = result[index]
}

If you want index from object, you can use index(of:) for that. 如果你想从对象索引,你可以使用index(of:)

if let index = result.index(of: obj) {
    print(index)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM