Is there a quick way to search if something exists in NSArray?

Currently, if I want to search if an object is in NSArray (not sorted) or not. I need to iterate over the array and check each object until I find one that matches my expectation.

I doubt this is performance, even if validation is just an if statement.

To improve search performance, is there a solution provided?

Or can I just sort the array in some way and use some way, like a binary search?

+4
source share
2 answers

Sorting, then the search will take longer than a loop repeating for each element of the array, since sorting based on comparison takes O (n * log (n)) at best, iterating over the array will take O (n) time for n elements in an array.

A pragmatic solution would be to use NSArray # containsObject if you already know the object.

Otherwise, you must implement your own comparison strategy and go through the array

+3
source

you can use quick listing. eg:

NSEnumerator * enumerator = [set objectEnumerator];

NSNumber *setObject ; while ((setObject = [enumerator nextObject]) != nil){ [gids appendString:[NSString stringWithFormat:@"%d",[setObject intValue]]]; } 
-1
source

All Articles