【问题标题】:When iterating an NSMutableArray, how to delete one object then insert multiple objects?迭代 NSMutableArray 时,如何删除一个对象然后插入多个对象?
【发布时间】:2016-04-04 06:09:35
【问题描述】:

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

任何想法将不胜感激!

【问题讨论】:

  • 你使用 Swift 还是 Objective-C ?只是想知道如何回答;)
  • 我正在使用 objc,谢谢
  • 好的,所以在这种情况下,您应该查看stackoverflow.com/questions/25238436/…,这几乎是您所需要的:)
  • 嗯,不完全是我需要的,但你的回答给了我一个线索,我想我有一些想法,我稍后会在代码中测试它。谢谢
  • 删除部分在我提供给您的链接中处理。您如何确定必须在已删除的索引处插入哪些对象以及必须插入多少个对象?

标签: ios objective-c algorithm nsmutablearray


【解决方案1】:

编辑: 正如@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];        
}];

【讨论】:

    【解决方案2】:

    [myMutableArray replaceObjectAtIndex:2 withObject:"5"]; 它会工作吗?

    【讨论】:

    • 这只会替换它,即 1 个对象对应 1。我猜 OP 要求多个对象对应 1 个
    • 是的,我要求用多个对象替换一个对象
    【解决方案3】:

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

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

    参考以下参考链接:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 我没有投反对票,但我赞成你的回答以抵消反对票,因为我认为你的意见很有价值:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多