Reputation: 67
I'm trying to fetch all my items from Core Data that doesn't have "X" in its allergens attribute.
func doesNotContain(attribute: String = "allergens", text: String) {
let request: NSFetchRequest<Dinner> = Dinner.fetchRequest()
let predicate = NSPredicate(format:"NOT \(attribute) CONTAINS %@", text)
request.predicate = predicate
do { items = try context.fetch(request) }
catch let error { print("Error: \(error)") }
}
For some reason this crashes with "EXC_BAD_ACCESS"
But it works perfectly fine when I'm trying to fetch with a predicate using:
func containsSearchWithNSPredicate(attribute: String, text: String) {
let request: NSFetchRequest<Dinner> = Dinner.fetchRequest()
let predicate = NSPredicate(format: "\(attribute) CONTAINS[cd] %@", text)
request.predicate = predicate
do { items = try context.fetch(request) }
catch let error { print("Error: \(error)") }
}
The attribute here is set to "name" when the function is called, and it's set to "allergens" in the first example
I've made sure that the attribute "allergens" is not nil, and I've also tried using %d instead of %@. The allergens attribute is an array, and that's why I'm using NOT CONTAINS
Upvotes: 1
Views: 366
Reputation: 67
Turns out that NSPredicate doesn't work with attributes marked as "Transformable" with a custom class of [String].
I made it work by instead of having an array, I made it to a String, separating each individual allergen with ";" to make it possible to divide into substrings later.
allergen example:
dinner.allergens = "Gluten;Dairy"
The NSPredicate:
let predicate = NSPredicate(format:"NOT (%K CONTAINS[cd] %@)",attribute, text)
The fetch request will now get all entities that does not have an allergen attribute containing text
Upvotes: 1