Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSSortDescriptor get key from core data in Swift 4

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)
like image 442
Wael Avatar asked Oct 28 '25 14:10

Wael


1 Answers

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")
like image 195
Martin R Avatar answered Oct 31 '25 04:10

Martin R