【问题标题】:What is the benefit of insertObject:atIndex: over replaceObjectAtIndex:withObject: on an NSMutableArrayinsertObject:atIndex: over replaceObjectAtIndex:withObject: 在 NSMutableArray 上有什么好处
【发布时间】:2012-12-18 20:43:47
【问题描述】:

当用 NSMutableArray 中的新值替换某个索引处的值时,旧值保存在内存中。要解决的问题是在每个循环之前初始化一个新的 NSMutableArray。

复制步骤:

- (id) init{
    self.overlays = [[NSMutableArray alloc] initWithCapacity: [self.anotherArray count]];
}

- (void) someOtherMethod{
    for(int i = 0 ; i < self.anotherArray ; i++){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        [view setBackgroundColor:[UIColor colorWithRed:0 
                                                green:0 
                                                 blue:0 
                                                alpha:1]];
        [view setAlpha: .2];
        [self.overlays insertObject:view atIndex: i]
    }
}

- (void) main{
    for(int i = 0 ; i < 4 ; i++){
        [myObject someOtherMethod];
    }
}

insertObject:atIndex 实际上会导致内存泄漏,因为它不会释放数组中该索引处的旧值。

我提交了错误报告,Apple 回复了:

insertObject:atIndex: 的行为符合定义。它正在插入,而不是替换。如果你想替换,你应该改用 -replaceObjectAtIndex:withObject:

insertObject:atIndex: 怎么可能有任何好处,因为您总是会丢失对该索引处旧对象的引用。

这仅仅是为了避免解决问题,因为它符合旧的文档定义吗?

【问题讨论】:

  • 你认为“插入”是什么意思?
  • 方法不同,所以名称不同。在索引处插入一个对象就是在某个索引处添加一个对象,在某个索引处替换一个对象基本上就是在数组的某个索引处取一个对象,然后用另一个对象替换它
  • 啊,我不知道我在想什么

标签: objective-c cocoa nsmutablearray automatic-ref-counting


【解决方案1】:

这两种方法做不同的事情。想象一下以下数组:

NSMutableArray *anArray = [@[ @1, @2, @3 ] mutableCopy];

如果您在位置1插入一个元素,像这样:

[anArray insertObject:@4 atIndex:1];

数组等于@[ @1, @4, @2, @3 ]。插入新元素而不删除另一个元素。

相反,如果您替换位置1的元素,如下所示:

[anArray replaceObjectAtIndex:1 withObject:@4];

你会得到@[ @1, @4, @3 ]。该位置的前一个对象被删除。

【讨论】:

    【解决方案2】:

    insertObject:atIndex 不会删除旧项目,正如您已经注意到的那样。相反,它会在您指定的索引处插入新项目。调用该方法后,数组元素计数加1。

    这与replaceObjectAtIndex:withOjbect 不同,后者是替代品。数组的元素计数保持不变。

    Insert 正是这样做的。考虑一个包含 5 个元素的数组:如果调用 [myArray insertObject:insertedObj atIndex:1];,myArray 实例现在有 6 个元素,insertedObj 插入到第一个索引处。

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 2023-02-20
      • 2012-07-17
      相关资源
      最近更新 更多