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

查看:713
本文介绍了在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天全站免登陆