Swift 4中Core Data的NSSortDescriptor如何避免硬编码键?
嘿,作为iOS和Core Data新手,你的这个顾虑太对了——硬编码属性字符串真的是个隐形坑,哪天字段名一改,APP直接崩溃,排查起来还麻烦。我给你几个实用的解决办法,完美避开硬编码的问题:
#keyPath语法 Swift自带的#keyPath会在编译阶段帮你检查属性名是否正确,要是你改了Core Data里的字段名但忘了更新代码,编译器直接就会报错,根本等不到运行时崩溃。用法超简单:
let sortDescriptor = NSSortDescriptor(key: #keyPath(TBL_Products.product_name), ascending: true)
要是你生成的NSManagedObject子类里把属性名改成了驼峰式(比如productName对应Core Data里的product_name),直接写#keyPath(TBL_Products.productName)就行,Xcode会自动帮你映射到正确的字段名。
先确保你已经给TBL_Products生成了对应的NSManagedObject子类(没生成的话,在Xcode里选Editor > Create NSManagedObject Subclass...就能生成),然后在子类里给每个字段加个静态字符串属性:
import CoreData class TBL_Products: NSManagedObject { // 对应Core Data里的product_name字段 static let productNameKey = "product_name" // 对应Quantity字段 static let quantityKey = "Quantity" }
之后创建排序描述符的时候直接用这个静态属性:
let sortDescriptor = NSSortDescriptor(key: TBL_Products.productNameKey, ascending: true)
这种方式很直观,新手一眼就能看懂,而且改字段名的时候只要更新静态属性的值就行,不用到处找硬编码的字符串。
如果你特别想实现类似TBL_Products.product_name.descriptor的调用方式,可以给NSManagedObject写个扩展,用KeyPath来生成排序描述符:
extension NSManagedObject { static func sortDescriptor<Value>(for keyPath: KeyPath<Self, Value>, ascending: Bool) -> NSSortDescriptor { let key = String(keyPath) return NSSortDescriptor(key: key, ascending: ascending) } }
使用的时候就可以这样写:
let sortDescriptor = TBL_Products.sortDescriptor(for: \.product_name, ascending: true)
不过说实话,这个方法比前两个稍微复杂一点,其实#keyPath已经完全能满足你的需求,而且更简洁。
总的来说,优先选#keyPath,编译时检查错误最靠谱;静态属性的方式也很适合新手快速上手。
内容的提问来源于stack exchange,提问作者Wael

