Should I check if an object exists in a collection before removing it?
cocoa, collections, objective-c
Solution
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:
This method uses `indexOfObject:` to locate matches and then removes them by using `removeObjectAtIndex:`. [...] If the array does not contain `anObject`, the method has no effect (although it does incur the overhead of searching the contents).
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 `NSArray`s aren't arrays.
Problem
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?