Search code examples
iosswiftcore-datakeynsmanagedobject

How to Derive a Core Data Attribute Key from an NSManagedObject Property?


Is there a way to retrieve the key of a Core Data entity's attribute directly from the property of the corresponding NSManagedObject? This would remove the need for reliance on string-based ('stringly-typed') code for some situations, thereby reducing the risk of error.

For example, I would want to replace the following:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdDate", ascending: false)]

...with something more like this:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: exampleNSManagedObject.createdDate.key, ascending: false)]

I know that .defaultSortDescriptors can be used to achieve some of this, but only for a fixed attribute. I also know that .entity.attributesByName.keys can be used to get the list of keys, but I haven't established a way to then automatically isolate the relevant one.


Solution

  • Is the #keyPath string expression what you are looking for? From the docs:

    You use the #keyPath string expression to create compiler-checked keys and key paths that can be used by KVC methods

    For example:

    fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ExampleNSManagedObject.createdDate), ascending: false)]