NSMutableArray - 在删除时禁用重新索引

3

For example I have array:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, nil];

数组看起来像这样:

0 => @1
1 => @2
2 => @3

然后我删除索引为0的对象

[array removeObjectAtIndex:0];

...而NSMutableArray会自动重新索引数组,因此数组看起来像这样:

0 => @2
1 => @3

问题:是否可以禁用自动数组重新索引?或者是否有类似的类可以替代NSMutableArray使用?谢谢。


@Rob 为什么那不是一个答案呢 :) ? - Guillaume Algis
3
你希望使用什么方法来替代重新索引?也许可以在删除索引处插入'[NSNull null]',而不是移除对象。 - Kirsteins
谢谢。我认为[NSNull null]会是解决方案。 - user1518183
2个回答

4

您不能使用不连续的索引,因此最好的方法是使用占位符对象来代替被移除的对象。

例如:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, nil];
[array replaceObjectAtIndex:0 withObject:[NSNull null]];

现在您将拥有:
0 => [NSNull null]
1 => @2
2 => @3

因此,非空对象的索引被保留。

2
不,你不能从NSMutableArray中删除对象而不更新索引。但是你可以使用NSMutableDictionary来实现所需的效果(在其中使用key(可以是NSNumber)而不是NSMutableArrayNSUInteger数值索引)。
NSMutableDictionary *dictionary = [@{@0 : @1,
                                     @1 : @2,
                                     @2 : @3} mutableCopy];

NSLog(@"before: %@", dictionary);

[dictionary removeObjectForKey:@0];

NSLog(@"after: %@", dictionary);

产生:

之前: {
    0 = 1;
    1 = 2;
    2 = 3;
}
之后: {
    1 = 2;
    2 = 3;
}

因此,不再是:

NSNumber *number = [array objectAtIndex:0];

您会使用:

NSNumber *number = [dictionary objectForKey:@0];

或者,可以选择:
NSNumber *number = array[0];

您需要使用:
NSNumber *number = dictionary[@0];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接