iosobjective-ccore-datansfetchedresultscontrollernscompoundpredicate

NSCompoundPredicate construction


Say I have this array of predicates in the feedDays array:

<__NSArrayM 0x7ff7f3cd1040>(
    feedDay == 1,
    feedDay == 2,
    feedDay == 4
)

I need to AND it with this statusPredicates array:

<__NSArrayM 0x7ff7f3cd1070>(
    is_neutered == 0 AND other_status == 0,
    is_neutered == 0 AND other_status == 1,
    is_neutered == 0 AND other_status == 2,
    is_neutered == 0 AND other_status == 3,
)

How can I combine these into one query? I assume I have to use NSCompoundPredicate but I can't figure out how to get it to AND two arrays of predicates together.


Solution

  • It seems to me that a combined predicate such as

    feedDay == 1 && feedDay == 2 ...
    

    would be always false.

    Thus what you perhaps mean is to combine each predicate with the neutered condition so that both conditions are true (and), and combine these individual groups so that either of these are true (or).

    If you combine the array with into one big compound with and it is bound to be always false. Assuming that the neutered condition is always the same,

    NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:
      @[[NSPredicate predicateWithFormat:@"is_neutered = 0"],
        [NSCompoundPredicate orPredicateWithSubPredicates:feedDays]]];
    

    That's pretty ugly, right? So I propose that you create an array with the possible values for feedDay and use the simple

    [NSPredicate predicateWithFormat:
         @"is_neutered = 0 && feedDay in %@", allowedFeedDays]