Say I have an object someObject and an NSMutableArray *someArray. I’m not sure if someObject is in the array, but if it is, I want to remove it. There are two options:
Case 1:
if([someArray indexOfObject:someObject] != NSNotFound)
[someArray removeObject:someObject];
Case 2:
[someArray removeObject:someObject];
In case 2, if the object doesn’t exist in the array, nothing happens. My question is, is case 2 more efficient, since in case 1 I’d have to search the array and see if it exists, and if it does, I remove it, but I’m guessing removeObject: searches the array again for that object?
Well, yes, it has to. There’s no way to find an object in a collection without looking for it.* The docs even say this:
You can of course imitate the framework and use
removeObjectAtIndex:yourself right after the search if you want.*This is faster than it might be (at worst O(log(N)) rather than O(N)) because
NSArrays aren’t arrays.