ARCのweakとstrongでちょっとハマった
NSMutableArrayにオブジェクトを入れてaddObjectして、UITableViewに表示させようとしていた。みんなやるよね、こういうコード。
NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:20]; Hoge *hoge = [Hoge new]; hoge.foo = @"foo"; hoge.bar = @"bar"; [arr addObject:hoge];
こんなコードを書いていた。Hogeクラスのプロパティはweakにしていた。
で、UITableViewのreloadDataを叩いてcellForRowAtIndexPathを見てみると、addObjectしたhogeのプロパティが全てnullになってた。weakからstrongにすると、nullではなくなった。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } Hoge *arr = [hogeArray objectAtIndex:indexPath.row]; cell.textLabel.text = hoge.foo; return cell; }
Hogeのプロパティがweakの場合、このコードだと同じ変数であるHoge *arrの中身が変わってしまうと今までの参照先をreleaseすることになるので、新しいオブジェクトを配列から取得したと同時にreleaseされるため常にnullが返されてしまいます、と。
勉強になりました。