如何恢复NSMutableArray的原始排序顺序?

时间:2012-04-21 01:02:10

标签: objective-c ios

我已将NSString标记为NSMutable数组。然后,我可以使用NSSortDescriptor按字符串的长度对该数组进行排序。然后我可以从最长的开始对某些单词执行方法。

这是我的问题所在。我现在需要恢复数组的原始排序顺序,以便我可以将数组运行回一个已编辑的字符串。

2 个答案:

答案 0 :(得分:2)

NSMutableArray对它之前的状态一无所知,只知道它的当前状态。可能有更优雅的解决方案,但您可以做的一件事是创建另一个存储原始排序顺序的数组。

答案 1 :(得分:2)

我的答案基本上就像史蒂夫一样,除了我反过来做 - 保持原始数组,创建一个排序副本,逐步完成排序副本进行处理然后抛出它离开了。所以,例如。

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
}