开发者

Preventing duplicate copies in a table view

开发者 https://www.devze.com 2023-01-18 16:45 出处:网络
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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号