在一次采访中,我被要求实现 NSArray 的 exchangeObjectAtIndex:withObjectAtIndex: 方法。我写了以下代码:
- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 {
id tmp = [self objectAtIndex:index1];
[self replaceObjectAtIndex:index1 withObject:[self objectAtIndex:index2]];
[self replaceObjectAtIndex:index2 withObject:tmp];
}
面试官说这是第一行的内存管理问题,我要赶上 bad_access_exc。他建议这样写:
- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 {
id tmp = [[[self objectAtIndex:index1] retain] autorelease];
[self replaceObjectAtIndex:index1 withObject:[self objectAtIndex:index2]];
[self replaceObjectAtIndex:index2 withObject:tmp];
}
我知道他的代码是正确的,但是由于 tmp 是局部变量并且将被分配,所以没有释放,一切都会好起来的。有什么错误吗?