[英]Remove duplicates from a NSMutableArray with objects added in a 'for' loop
Now, I've looked up on this on here and google, and it seems everyone uses NSSet
to remove dupes. 现在,我在这里和google上进行了查找,似乎每个人都使用
NSSet
来删除重复项。 This is cool and all, but it seems that this method removes the sorting as well. 一切都很酷,但是似乎该方法也消除了排序。
Is there 1) A way to sort NSSet alphabetically? 有1)一种按字母顺序对NSSet排序的方法吗? 2) A better way to remove dupes in
NSMutableArray
in or outside the for
loop where I add them to the array by reading them from a .csv
file. 2)一种更好的方法,以除去在愚弄
NSMutableArray
中或外for
其中I通过从读取他们将它们添加到阵列循环.csv
文件。
Thanks:) 谢谢:)
I believe you want to be using an NSOrderedSet
. 我相信您想使用
NSOrderedSet
。 Here's the documentation on it: 这是关于它的文档:
http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSOrderedSet_Class/Reference/Reference.html http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSOrderedSet_Class/Reference/Reference.html
You can construct an NSOrderedSet
* from your array; 您可以从数组构造一个
NSOrderedSet
*; using +orderedSetWithArray:
will preserve the array's existing order. 使用
+orderedSetWithArray:
将保留数组的现有顺序。 If it's not already in the correct order, you can't sort the set directly, so there's little point in using an ordered set, but you can easily construct a regular NSSet
and sort that into another array, using -sortedArrayUsingDescriptor:
, or even better allObjects
, followed by any of NSArray
's sorting methods. 如果尚未按照正确的顺序进行排序,则无法直接对集合进行排序,因此使用有序集合毫无意义,但是您可以轻松地构造一个常规的
NSSet
并使用-sortedArrayUsingDescriptor:
排序到另一个数组中,甚至更好的allObjects
,然后是NSArray
的任何排序方法。
On the other hand (it's possible I'll get some nasty comments about this, but...), since NSArray
and NSSet
seem to be built on top of the same hash table functionality , you could just do this: 另一方面(由于这我可能会收到一些讨厌的评论,但是...),因为
NSArray
和NSSet
似乎是基于相同的哈希表功能 构建的 ,您可以这样做:
id newObj = // Acquire new object from wherever
while( newObj ){
if( ![arrayImConstructing containsObject:newObj] ){
[arrayImConstructing addObject:newObj]
}
newObj = // Acquire next object
}
This is basically what an ordered set has to do when you construct it anyways, and it's quite likely that your array is small enough (if you're putting it into a UIPicker
) that you won't notice a performance difference at all. 从根本上讲,这就是有序集合在构造时必须要做的事情,而且很有可能数组足够小(如果将其放入
UIPicker
),根本不会注意到性能差异。 Still, measure the two , and then decide. 仍然, 测量两个 ,然后决定。
* NSOrderedSet
is available on iOS > 5.0 (or OS X > 10.7). *
NSOrderedSet
在iOS> 5.0(或OS X> 10.7)上可用。
NSOrderedSet使您可以订购集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.