2015-02-05 58 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]; 
} 
相關問題