迭代NSMutableArray时,如何删除一个对象然后插入多个对象?

When iterating an NSMutableArray, how to delete one object then insert multiple objects?

例如,如果我们有一个 NSMutableArray 实例,其中有 10 个对象。遍历的时候,我们发现要删除对象a[2]和a[8],然后在a[2]处连续插入3个对象,在a[8]处连续插入4个对象,如何在最短时间内做到这一点费用?

如有想法将不胜感激!

[myMutableArray replaceObjectAtIndex:2 withObject:"5"]; 有用吗?

首先你必须删除对象然后使用下面的代码行插入多个对象:

NSMutableOrderedSet *orderedSet = [[NSMutableOrderedSet alloc] init];
[orderedSet insertObjects:@[@"Eezy", @"Tutorials"] atIndexes:
                       [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)]];
NSLog(@"Result: %@", orderedSet);

参考以下参考 link:

http://ios.eezytutorials.com/nsmutableorderedset-by-example.php#.VwIJIhN95fg

编辑: 正如@trojanfoe 指出的那样,很高兴补充一点,您永远不应该在迭代数组时编辑它。许多不同语言的许多集合 类 都是如此;不只是 NSMutableArray & Objective-C。这样做很容易导致索引越界。


对于你的问题,我们分两次来做。 首先,我们要保存我们要删除的索引,所以我们将迭代 sourceArray。

NSMutableArray * indexesToRemove = [NSMutableArray array];

[sourceArray enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if (obj.integerValue%2 == 1) {
        // Insert at first position
        [indexesToRemove insertObject:@(idx) atIndex:0];
    }
}];

将索引保存在数组中而不是集合中很重要,因为您以后要插入对象。此外,在数组的开头添加新项很重要,因此您将从最大索引到最小索引进行迭代,而不必根据先前添加的项移动索引。

现在,您可以在新的迭代中(这次是在索引数组上)删除项目并根据您保存的索引添加新项目:

[indexesToRemove enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL * _Nonnull stop) {

    NSUInteger indexToRemove = obj.unsignedIntegerValue;

    // Delete the item from the source array
    [sourceArray removeObjectAtIndex:indexToRemove];

    // Create the items you want to insert, do whatever you want in this method :]
    NSArray * itemsToAdd = [self generateElementsToAddAtIndex:indexToRemove];

    // Create the indexSet according to the start index and the number of objects you want to insert
    NSIndexSet * indexSet = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(indexToRemove, itemsToAdd.count)];

    // Insert the objects
    [sourceArray insertObjects:itemsToAdd atIndexes:indexSet];        
}];

对于这么小的数组和如此多的操作,我认为用一个新数组替换数组是一个不错的选择 - 为了性能和清晰度。