3

あるインタビューで、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 はローカル変数であり、代入されるので、解放する必要はなく、すべて問題ありません。エラーはありますか?

4

2 に答える 2