insertObject:atIndex:overObjectObjectItIndex:withObject:on NSMutableArray的好处是什么

Jes*_*rle -3 cocoa objective-c nsmutablearray automatic-ref-counting

当使用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];
    }
}
Run Code Online (Sandbox Code Playgroud)

insertObject:atIndex有效地导致内存泄漏,因为它不会释放该索引处的数组中的旧值.

我提交了一份错误报告,Apple回答说:

insertObject:atIndex:表现为已定义.它正在插入,而不是替代.如果要替换,则应使用-replaceObjectAtIndex:withObject:

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

这是否只是为了避免修复问题,因为它符合旧的文档定义?

Jon*_*pan 12

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

NSMutableArray *anArray = [@[ @1, @2, @3 ] mutableCopy];
Run Code Online (Sandbox Code Playgroud)

如果在位置插入元素1,如下所示:

[anArray insertObject:@4 atIndex:1];
Run Code Online (Sandbox Code Playgroud)

数组变得相等@[ @1, @4, @2, @3 ].插入新元素时不会删除其他元素.

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

[anArray replaceObjectAtIndex:1 withObject:@4];
Run Code Online (Sandbox Code Playgroud)

你得到@[ @1, @4, @3 ].删除该位置的上一个对象.