I have a bit of a hard time writing a predicate for my search functionality and thought you'd be bale to help. So basically I have two arrays of NSNumbers. I want my predicate to satisfy the following:<pre class="lang-none prettyprint-override">
If a number's integerValue in array A matches any integerValue in array B.
I don't want to use any sort of loop for this solution. Here's what I have so far
ANY integerValue == ANY //how do I pass the entire array here and ask for the integerValue of each member?Answer1:
The ANY operator will handle that.
Since it is a bit difficult to say from your question which of the arrays is "self" in normal predicate parlance, I'll write it without a self:
NSArray *arrayA = @[@2, @3, @7]; NSArray *arrayB = @[@2, @4, @9]; NSPredicate *pred = [NSPredicate predicateWithFormat: @"ANY %@ IN %@", arrayA, arrayB];
Due to the lack of a "self", it will have to be evaluated with
nil as the object, but that works fine:
BOOL matched = [pred evaluateWithObject: nil];
If you prefer to have a "self" in the predicate, you can just enter it:
NSPredicate *pred = [NSPredicate predicateWithFormat: @"ANY self IN %@", arrayB]; BOOL matched = [pred evaluateWithObject: arrayA];
The result is the same.<h3>A small conceptual comment</h3>
The predicate above evaluates to true if any integer is included in both arrays, which is how I read your question.
This means that, conceptually speaking, you seem to be testing whether two sets of numbers intersect each other.
intersectsSet: checks that, so another way to do the test would be to keep your numbers as sets and test for intersection:
matched = [setA intersectsSet: setB];Answer2:
I know it's not precisely what you asked for (predicates and all) but another way is to use
- (id) firstObjectCommonWithArray:(NSArray *)otherArray, which would return
nil if no common object can be found.
BOOL arraysIntersect = [array1 firstObjectCommonWithArray:array2] != nil;
One caveat though is that it would use its own object equality rules when comparing two objects, meaning if two objects are NSNumber instances, it will compare them using
compare: method. But the same goes for the predicate-based solution proposed so far.