NSPredicate for two NSNumber arrays

落爺英雄遲暮 提交于 2019-12-25 11:25:09

问题


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:

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? 

回答1:


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.

A small conceptual comment

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. NSSet's method 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];



回答2:


I know it's not precisely what you asked for (predicates and all) but another way is to use NSArray's - (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 NSNumber's compare: method. But the same goes for the predicate-based solution proposed so far.



来源:https://stackoverflow.com/questions/17150697/nspredicate-for-two-nsnumber-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!