Check if NSArray contains some int

Henry picture Henry · Aug 7, 2011 · Viewed 11.5k times · Source

I have a NSMutableArray of NSNumbers. Basically I just want to check if any of the NSNumbers in the array = some value.

I could iterate through the array, checking one by one, by this is by no means optimal.

I also tried and failed using containsObject, because this only works if the id's are the same.

I read something about NSPredicate, this seems like a good solution, but I am not sure on how to use it with an NSArray.

Any answer is appreciated.

Thanks

Answer

Tieme picture Tieme · Dec 19, 2012

Inspired by bernstein I looked up some more info about the and i found CFArrayContainsValue

BOOL CFArrayContainsValue(CFArrayRef theArray, CFRange range, const void *value);

Example:

NSArray *numbers;
NSNumber *value;
BOOL found = CFArrayContainsValue ( (__bridge CFArrayRef)numbers, 
                                    CFRangeMake(0, numbers.count), 
                                    (CFNumberRef)value );

Works like a charm and is really fast!