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
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!
NSPredicate *valuePredicate=[NSPredicate predicateWithFormat:@"self.intValue == %d",[myValueNumber intValue]];
if ([[numbersArray filteredArrayUsingPredicate:valuePredicate] count]!=0) {
// FOUND
}
else {
//NOT FOUND
}
Iterating through the array is the best approach here. This is exactly what the containsObject
method is doing under the covers. You could sort the array, but that wouldn't give you very much in terms of efficiency.
If you want to be able to look up values quicker than O(n), NSArray/NSMutableArray
is probably not the right data structure for you.
a little late, but since the array is already ordered (sorted) you should use CFArrayBSearchValues() which does binary search.
example with numbers:
NSArray *array; // or NSMutableArray
NSNumber *value; // search value
CFArrayBSearchValues((__bridge CFArrayRef)array, CFRangeMake(0, array.count),
(CFNumberRef)value, (CFComparatorFunction)CFNumberCompare, NULL);
Iterating through NSArray is OK if you don't do it too much. And that's what "containObject" does. But I found that when you need lots and lots of those checks, especially if the arrays are big, it will slow your app...
So if it's a check you need to do often, you can always dictionary instead of array. Where the key will be the NSNumber, and the field will be the number of times it appears in the array. Then, you use "ObjectForKey" to check if the number is in the array, you use "allKeys" to get all the values if needed, etc...
Good luck
You can simply check like this:
if ([myArray indexOfObject:@(myNumber)] == NSNotFound) {
NSLog(@"myArray' contauns 'myNumber");
}
Keep Coding.......... :)
精彩评论