Preventing duplicate copies in a table view
I have an NSMutableArray that I display through a table view. The problem is that when I add objects to this array, I don't want to have dupl开发者_StackOverflowicates.
If I create an NSMutableSet from the NSMutableArray, then add objects to the NSMutableSet and then convert it back to an NSMutableArray, is that any more efficient than checking the NSMutableArray through a loop for duplicates before adding an item?
Generally yes, it would be more efficient to use a set. Constructing a set of n items is O(n log n)
. Finding all the duplicates in an array by just looping through it will be O(n^2)
. (If you're really determined you could get O(n log n), but you'd have to kinda rewrite what set already does.)
you can check if the object your adding exists by using
- (NSUInteger)indexOfObject:(id)anObject
if the object exists in the array it will give you an index else it returns
NSNotFound
so you can do an if before adding elements to your array.
i think that its a little better in memory wise because you don't create to objects.
Hope this helps
精彩评论