从Objective-C中的NSMutableArray中删除重复值的最佳方法? [英] The best way to remove duplicate values from NSMutableArray in Objective-C?

查看:25
本文介绍了从Objective-C中的NSMutableArray中删除重复值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Objective-C 中从 NSMutableArray 中删除重复值 (NSString) 的最佳方法是什么?

The best way to remove duplicate values (NSString) from NSMutableArray in Objective-C?

这是最简单和正确的方法吗?

Is this the easiest and right way to do it?

uniquearray = [[NSSet setWithArray:yourarray] allObjects];

推荐答案

如果你不担心对象的顺序,你的 NSSet 方法是最好的,但是如果你'不担心顺序,那你为什么不把它们存储在 NSSet 开始呢?

Your NSSet approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet to begin with?

我在 2009 年写了下面的答案;2011 年,Apple 将 NSOrderedSet 添加到 iOS 5 和 Mac OS X 10.7.曾经的算法现在是两行代码:

I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:

NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];

<小时>

如果您担心顺序并且您在 iOS 4 或更早版本上运行,请遍历数组的副本:


If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:

NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
    if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
        [mutableArray removeObjectAtIndex:index];
    }
    index--;
}
[copy release];

这篇关于从Objective-C中的NSMutableArray中删除重复值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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