创建唯一的NSMutableArray或NSMutableSet [英] Make unique NSMutableArray or NSMutableSet

查看:251
本文介绍了创建唯一的NSMutableArray或NSMutableSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在通过 NSMutableArray (或 NSMutableSet )枚举查找重复项并删除它们。 p>

例如,如果array / set的值 [@a,@b,@b,@c] ,最终结果应为 [@a,@b,@c]



因为我比较 NSStrings ,我使用 isEqualTo:方法来检查字符串是否相等。



是否有更有效的方法来删除重复条目,而不是循环遍历它们,并检查是否存在重复?

解决方案

NSSet 完全符合您的意图:它是唯一项目的(无序)集合。因此,你可以在数组中找到唯一的项,如下:

  NSSet * uniqueElements = [NSSet setWithArray:myArray]; 

//遍历唯一的项目
for(uniqueElements中的id元素){
//做某事
}

NSSet 最有可能使用散列算法进行插入O(1) (n ^ 2)来检查每个项目是否是唯一的通过迭代),但苹果文档不作这样的保证,所以你可能不应该指望那个实现细节。



如果由于某些原因需要在排序(有序)集合中保留唯一项目,则可以将该集合转换为 - [NSSet allObjects] 然后对结果数组排序。


I'm currently enumerating through NSMutableArray (or NSMutableSet) elements to find duplicates and remove them.

For example, if array/set has values [@"a", @"b", @"b", @"c"], the end result should be [@"a", @"b", @"c"].

Since I'm comparing NSStrings, I'm using isEqualTo: method to check if strings are equal.

Is there a more efficient way to do remove duplicate entries than to loop through all of them and check if duplicate exists?

解决方案

An NSSet does exactly what you're trying to do: it is a (unordered) collection of unique items. So, you can find the unique items in your array like so:

NSSet *uniqueElements = [NSSet setWithArray:myArray];

// iterate over the unique items
for(id element in uniqueElements) {
  // do something
}

NSSet most likely uses a hash algorithm to make insertion O(1) (compared to O(n^2) to check if each item is unique by iteration), but the Apple documentation does not make such a guarantee so you probably shouldn't count on that implementation detail.

If, for some reason you need to keep the unique items in a sorted (ordered) collection, you can turn the set back into an array with -[NSSet allObjects] and then sort the resulting array.

这篇关于创建唯一的NSMutableArray或NSMutableSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆