2012-04-21 55 views
2

我已經將一個NSString標記爲一個NSMutable數組。然後,我可以使用NSSortDescriptor按字符串的長度對該數組進行排序。然後我可以從最長的單詞開始執行某些單詞。如何恢復NSMutableArray的原始排序順序?

這是我的問題表面。我現在需要恢復數組的原始排序順序,以便我可以將數組運行回編輯後的字符串。

回答

2

我的答案基本上和Steve的答案一樣,只不過我反其道而行 - 保留原始數組,創建一個有序的副本,逐步完成處理後的排序副本,然後將其丟棄。所以,例如

NSArray *yourOriginalArray = ...whatever...; 

// do processing 
for(id object in [yourOriginalArray sortedArrayUsing<whatever means>]) 
{ 
    // if you're doing processing that doesn't change the identity of 
    // the object then there's no need to worry about this, but supposing 
    // you want to adjust the identity (eg, the source array is full of 
    // immutable objects and you want to replace them) then... 

    NSUInteger originalIndex = [yourOriginalArray indexOfObject:object]; 

    id replacementObject = [self mutatedFormOf:object]; 
    [yourOriginalArray replaceObjectAtIndex:originalIndex 
        withObject:replacementObject]; 
    // of course, this is only if yourOriginalArray is mutable 
} 
+0

謝謝你,我認爲這正是我需要通過我的障礙。 – noahread 2012-04-24 14:59:16

2

NSMutableArray不知道它的前一個狀態,只是它的當前狀態。有可能更優雅的解決方案,但你可以做的一件事是創建另一個數組,存儲原始排序順序。