Wae*_*ael 4 sorting core-data ios swift
我是 IO 开发和核心数据的新手。
在我的应用程序中,我想使用 NSSortDescriptor 对数据进行排序,然后再将其提取到我的表视图中。
在我的核心数据中,我有一个表“TBL_Products”,其中包含两个字段“product_name”和“Quantity”
下面的代码工作得很好
let MySortDescriptor = NSSortDescriptor(key: "product_name" , ascending: true)
Run Code Online (Sandbox Code Playgroud)
但我讨厌的是我对键名称进行硬编码,因此如果列名称已更改,应用程序将崩溃。
有没有办法做到这样的事情(下面的代码不起作用):
let MySortDescriptor = NSSortDescriptor(key: TBL_Products.product_name.descriptor , ascending: true)
Run Code Online (Sandbox Code Playgroud)
使用可以使用#keyPath指令:
NSSortDescriptor(key: #keyPath(TBL_Products.product_name), ascending: true)
Run Code Online (Sandbox Code Playgroud)
编译器将其替换为包含属性名称的字符串。它在核心数据谓词中也很有用,例如
NSPredicate(format: "%K == %@", #keyPath(TBL_Products.product_name), "someProduct")
Run Code Online (Sandbox Code Playgroud)
请注意,在 Swift 5 中,这已更新为使用\.语法而不是#keypath指令:
NSSortDescriptor(key: \TBL_Products.product_name, ascending: true)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2668 次 |
| 最近记录: |