Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data Filter Predicate With An Array Swift

I am trying to pull objects out of my core data store by passing in an array of strings, and pulling only the objects that have a category matching what's in the array.

I have been able to get this code to work, except that it only uses the first item in the array, and won't iterate through the array and match the rest of the items.

This is the code that works for that. I am using the NSPredicate overload that accepts and array.

    func filterTopicCategories() {
        fetchController.topicFetchRequest.predicate = NSPredicate(format: "topicCategory == %@", argumentArray: selectedCategories)
        topicsToSelectFrom = fetchController.fetchTopics()
        }

I've poured through that Apple docs on predicates and all that, and can't seem to quite figure it out. I've spent a few hours searching around google as well. I am not sure if I am just not understanding something correctly, or if I am just doing it completely wrong, I am not sure. Any help would be greatly appreciated.

Thanks

like image 591
bshock84 Avatar asked Apr 16 '17 09:04

bshock84


1 Answers

The parameter argumentArray is for an array of values to replace the placeholders like %@ in the format string.

You are looking for the IN operator:

IN

Equivalent to an SQL IN operation, the left-hand side must appear in the collection specified by the right-hand side. For example, name IN { 'Ben', 'Melissa', 'Nick' }. The collection may be an array, a set, or a dictionary — in the case of a dictionary, its values are used. In Objective-C, you could create a IN predicate as shown in the following example:

NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection]; 

where aCollection may be an instance of NSArray, NSSet, NSDictionary, or of any of the corresponding mutable classes.

So if topicCategory is a string write

fetchController.topicFetchRequest.predicate = NSPredicate(format: "topicCategory IN %@", selectedCategories)
like image 162
vadian Avatar answered Sep 27 '22 17:09

vadian