在 Objective-C 中从 NSMutableArray
中删除重复值(NSString
)的最佳方法?
这是最简单和正确的方法吗?
uniquearray = [[NSSet setWithArray:yourarray] allObjects];
最佳答案
如果您不担心对象的顺序,您的 NSSet
方法是最好的,但话又说回来,如果您不担心顺序,那么为什么不存储以 NSSet
开头?
我在 2009 年写了下面的答案; 2011 年,Apple 将 NSOrderedSet
添加到 iOS 5 和 Mac OS X 10.7。原来的算法现在变成了两行代码:
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
如果您担心顺序并且您在 iOS 4 或更早版本上运行,请遍历数组的副本:
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];
关于ios - 在 Objective-C 中从 NSMutableArray 中删除重复值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1025674/