2015-02-05 55 views
0

我能想出各种各样的方式来实现这一点,但我正在寻找最优雅的,习惯的方法在Ojective-C要做到这一点:在Objective-C中生成重排序数组的习惯用法是什么?

我的按字母顺序排序的货币代码从[NSLocale ISOCurrencyCodes];数组。现在我想在数组的开头使用最常用的五种货币生成一个新数组,其余货币仍按字母顺序排列。

所以,任务是:将一些数组的元素移动到新数组的开始处,然后按原始顺序移动剩余的元素,但不将元素移动到前面并且没有任何间隙。

我目前的解决办法是:

NSMutableArray *mutableCurrencyList; 
mutableCurrencyList = [[NSLocale ISOCurrencyCodes] mutableCopy]; 
[mutableCurrencyList removeObject:@"USD"]; 
[mutableCurrencyList removeObject:@"EUR"]; 
[mutableCurrencyList removeObject:@"JPY"]; 
[mutableCurrencyList removeObject:@"GBP"]; 
[mutableCurrencyList removeObject:@"CAD"]; 
[mutableCurrencyList insertObject:@"USD" atIndex:0]; 
[mutableCurrencyList insertObject:@"EUR" atIndex:1]; 
[mutableCurrencyList insertObject:@"JPY" atIndex:2]; 
[mutableCurrencyList insertObject:@"GBP" atIndex:3]; 
[mutableCurrencyList insertObject:@"CAD" atIndex:4]; 
+1

也许我错过了你的问题的主旨,但我按照标准#1(最常用)排序,删除前5个元素,然后按标准#2(alpha)对其余元素进行排序,然后将两个元素简单地“拼接”在一起。所以,它分解为:1.排序2.采取3.排序4.针。你是要求一个这样的算法,还是实际的Obj-C代码来获得这个? – mbm29414 2015-02-05 13:03:53

+0

@ mbm29414不,这确实是一个微不足道的问题。我刚刚意识到,我经常做的事情比必要的更复杂,因为我不熟悉一种语言的常见成语。 [尤其是集合类](http://stackoverflow.com/questions/27986199/idiomatic-way-to-detect-sequences-of-x-times-same-object-in-an-array-in-smalltal)。 – MartinW 2015-02-05 13:09:57

+1

我想你会让事情变得更加复杂,因为你使用的是像“惯用”这样的词,而不是简单地考虑用来做某事的顺序。 – 2015-02-05 13:32:38

回答

2

答案取决于你如何确定哪些是5个最常用的货币。从你的编辑看来,你有这些5的静态列表,所以下面的方法是一种方法来做你在问什么:

- (NSArray *)orderedCurrencies { 
    // You might determine this list in another way 
    NSArray *fiveMostUsed   = @[@"USD", @"EUR", @"JPY", @"GBP", @"CAD"]; 
    // You already know about getting a mutable copy 
    NSMutableArray *allCurrencies = [[NSLocale ISOCurrencyCodes] mutableCopy]; 
    // This removes the 5 most-used currencies 
    [allCurrencies removeObjectsInArray:fiveMostUsed]; 
    // This sorts the list of the remaining currencies 
    [allCurrencies sortUsingSelector:@selector(caseInsensitiveCompare:)]; 
    // This puts the 5 most-used back in at the beginning 
    [allCurrencies insertObjects:fiveMostUsed atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 5)]]; 
    // This converts the mutable copy back into an immutable NSArray, 
    // which you may or may not want to do 
    return [allCurrencies copy]; 
} 
相关问题