Home > Enterprise >  NSPredicate not working on Swift (CoreData)
NSPredicate not working on Swift (CoreData)

Time:04-30

I have an entity with 1 attribute (Int) and a relation with another entity. I've created an object with an attribute and a relation and added it to the database. If I fetch all the objects in the entity I can see this one has been created, but I can't using NSPredicate with the correspondent attribute and relation.

fetchRequest.predicate = NSPredicate(format: "(int_attribute == %@) AND (relation_entity like %@)", int_value, relation_object)
let list = (try? context.fetch(fetchRequest)) ?? []

After doing this, list is empty. And the same happens if I use NSPredicate with just int_attribute. Context is a reference to a class DataController from ObservableObject where I have a NSPersistentContainer and init() function with loadPersistentStores.

CodePudding user response:

In predicates, %@ expects an object. It's not a general "replace this" indicator, and there are different specifiers for different data types. If you're matching primitive types you need something else. For integers, try %d. For other things, look up printf-style format specifiers.

  • Related