【发布时间】: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