Search code examples
iosswiftnspredicate

NSPredicate format dynamically use property name


I use this predicate for fetching objects from CoreData:

NSPredicate.init(format: "id in %@", ids)

So, my class has property called "id".

Is it possible to use the dynamic name of the property instead of hardcoding "id"?

The problem, at least for me, is that in case I change my property's name, I would need to change all predicates where it is used.

Instead I would want to use something like

NSPredicate.init(format: "%@ in %@", #keyPath(MyClass.id), ids)

This gives me a Predicate "id" in <listOfIDs>, while to make it works it requires id in <listOfIDs>

I understand this is very strange 'problem', but I really like to not use any of hardcoded properties' names in cases like this...


Solution

  • Yes, it is possible, you just need to use "%K" instead of "%@".

    NSPredicate.init(format: "%K in %@", #keyPath(MyClass.id), ids)