UICollectionViewでのセルの再利用

UICollectionView ではあらかじめセルのクラスを登録しておくことで、再利用可能なセルがない場合に新しく作成したものを返してくれるようになっています。
そのため dequeueReusableCellWithReuseIdentifier: が nil を返しません。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    ...

    return cell;
}

登録には registerClass:forCellWithReuseIdentifier:registerNib:forCellWithReuseIdentifier: といったメソッドが用意されていて、Storyboard でセルを作成してある場合は自動的に登録されます。 クラスを登録した場合には initWithFrame: で、Nib を登録した場合には awakeFromNib でセルの初期化を知ることができます。

この新しい仕組みは iOS 6.0 から追加されたもので、UITableView にも同じ仕組みが導入されたようです。
Master-Detail Application のテンプレートでは既に新しい方式に変更されています。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    ...

    return cell;
}

今まではこんな風に書いてきました。

- (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];
    }
    
    ...
    
    return cell;
}

今更感あふれる内容ですが、これで。