I am new to IOs developement and core Data.
In my application I want to use NSSortDescriptor to sort Data before fetching it to my tableview.
In my core data I have one table "TBL_Products" with two fields "product_name" and "Quantity"
The code below work perfectly fine
let MySortDescriptor = NSSortDescriptor(key: "product_name" , ascending: true)
But what I hate about it is I am hard coding the key name so the app will crash if the column name has been changed.
Is there is a way do to something like this (the code below not working):
let MySortDescriptor = NSSortDescriptor(key: TBL_Products.product_name.descriptor , ascending: true)
Use can use #keyPath directive:
NSSortDescriptor(key: #keyPath(TBL_Products.product_name), ascending: true)
The compiler replaces that with a string containing the property name. It is also useful in Core Data predicates, e.g.
NSPredicate(format: "%K == %@", #keyPath(TBL_Products.product_name), "someProduct")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With