如何将NSArray的字符串转换为一个唯一字符串数组,顺序相同? [英] How to turn an NSArray of strings into an array of unique strings, in the same order?

查看:123
本文介绍了如何将NSArray的字符串转换为一个唯一字符串数组,顺序相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有NSArray字符串

If you have an NSArray of strings

{ @"ONE", @"ONE", @"ONE", "TWO", @"THREE", @"THREE" }

如何将其转换为

{ @"ONE", @"TWO", @"THREE" }

..其中数组的顺序与原始顺序相同。我认为您可以将数组转换为NSSet以获取唯一的项目,但如果您将其转回数组,则无法保证获得相同的顺序..

..where the array follows the same order as the original. I think that you can turn an array into an NSSet to get unique items, but if you turn it back into an array you are not guaranteed to get the same order..

推荐答案

我最初的想法是你能做到:

My initial thought was that you could do:

NSArray * a = [NSArray arrayWithObjects:@"ONE", @"ONE", @"ONE", @"TWO", @"THREE", @"THREE", nil];
NSLog(@"%@", [a valueForKeyPath:@"@distinctUnionOfObjects.self"]);

但这不保持秩序。因此,你必须手动完成:

But that does not maintain order. Therefore, you have to do it manually:

NSArray * a = [NSArray arrayWithObjects:@"ONE", @"ONE", @"ONE", @"TWO", @"THREE", @"THREE", nil];
NSMutableArray * unique = [NSMutableArray array];
NSMutableSet * processed = [NSMutableSet set];
for (NSString * string in a) {
  if ([processed containsObject:string] == NO) {
    [unique addObject:string];
    [processed addObject:string];
  }
}

我使用 NSMutableSet 用于确定我之前是否已经遇到此条目(而不是 [unique containsObject:string] ,因为一个集合将具有O(1查找时间,并且数组有O(n)查找时间。如果你只处理少量对象,那么这无关紧要。但是,如果源数组非常大,那么使用set来确定唯一性可能会增加一点速度提升。(但是,您应该使用Instruments来分析您的代码并查看是否有必要)

I use an NSMutableSet for determining if I've already come across this entry before (as opposed to [unique containsObject:string], since a set will have O(1) lookup time, and an array has O(n) lookup time. If you're only dealing with a small number of objects, then this won't matter. However, if the source array is very large, then using the set to determine uniqueness may add a bit of a speed boost. (however, you should use Instruments to profile your code and see if it's necessary)

这篇关于如何将NSArray的字符串转换为一个唯一字符串数组,顺序相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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