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



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

这就是我的问题浮出水面的地方。我现在需要恢复数组的原始排序顺序,以便我可以将数组运行回编辑的字符串。

我的答案基本上与 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
}

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

最新更新