在 Objective-C 中生成重新排序的数组的惯用方法是什么?

What's the idiomatic way to generate a reordered array in Objective-C?

我可以想出各种方法来实现这一点,但我正在寻找 Ojective-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];

答案取决于您如何确定最常用的 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];
}