【问题标题】:NSSortDescriptor get key from core data in Swift 4NSSortDescriptor 从 Swift 4 的核心数据中获取密钥
【发布时间】:2018-01-25 10:53:49
【问题描述】:

我是 IO 开发和核心数据的新手。

在我的应用程序中,我想使用 NSSortDescriptor 对数据进行排序,然后再将其提取到我的 tableview 中。

在我的核心数据中,我有一个表“TBL_Products”,其中包含两个字段“product_name”和“Quantity”

下面的代码运行良好

let MySortDescriptor = NSSortDescriptor(key: "product_name" , ascending: true)

但我讨厌它是我对键名进行硬编码,因此如果更改列名,应用程序将崩溃。

有没有办法解决这样的事情(下面的代码不起作用):

let MySortDescriptor = NSSortDescriptor(key: TBL_Products.product_name.descriptor , ascending: true)

【问题讨论】:

    标签: ios swift sorting core-data


    【解决方案1】:

    使用可以使用#keyPath指令:

    NSSortDescriptor(key: #keyPath(TBL_Products.product_name), ascending: true)
    

    编译器将其替换为包含属性名称的字符串。 它在 Core Data 谓词中也很有用,例如

    NSPredicate(format: "%K == %@", #keyPath(TBL_Products.product_name), "someProduct")
    

    【讨论】:

      【解决方案2】:

      请注意,在 Swift 5 中,这已更新为使用 \. 语法而不是 #keypath 指令:

      NSSortDescriptor(key: \TBL_Products.product_name, ascending: true)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-30
        相关资源
        最近更新 更多