gpt4 book ai didi

ios - NSSortDescriptor 从 Swift 4 的核心数据中获取键

转载 作者:可可西里 更新时间:2023-11-01 00:55:56 25 4
gpt4 key购买 nike

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

在我的应用程序中,我想在将数据提取到我的 TableView 之前使用 NSSortDescriptor 对数据进行排序。

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

下面的代码工作得很好

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

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

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

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

最佳答案

使用可以使用#keyPath指令:

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

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

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

关于ios - NSSortDescriptor 从 Swift 4 的核心数据中获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48441124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com