2014年5月1日木曜日

UITableView、forIndexPath:indexPathを付けるとdequeueReusableCellWithIdentifier:@hogeが失敗する


チュートリアルなんかでよくみるやーつ

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

この通りにしても…

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

と落ちてしまいハマることがある。
ぐぐると、PrototypeCellにIdentifer設定してる?みたいな話か(当然してますよねー)
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)...
と、forIndexPathを切って、作れてなければ作ればいいんだよ。
って解決方法ばかり出てくる。
実際まあこれで解決することもあるんだけど、なんか、もやーん。

そんなとき、あと1個だけチェックしてみません?
そのエラーのでるビュー、こんな感じでStoryBoardで作ったものを手動で作ってたりする場合。

ErrorDeruViewController *view = [[ErrorDeruViewController alloc]init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:view];
nav.modalPresentationStyle = UIModalTransitionStyleFlipHorizontal;

[self presentViewController:nav animated:YES completion:nil];


古めの記事なんかでは、モーダル表示するのはこうですって紹介されてたりするので
コピペるとハマります。
こういう呼び方をすると、Storyboardとカスタムクラスが結び着かないので
そんなIdentiferのついたCellが見つからないけど…ってことで落ちてるみたいです。
なので

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ErrorDeruViewController *view = [storyBoard instantiateViewControllerWithIdentifier:@"ErrorDeruViewControllerId"];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:view];
nav.modalPresentationStyle = UIModalTransitionStyleFlipHorizontal;

[self presentViewController:nav animated:YES completion:nil];


みたいな感じで、StoryBoardからviewのインスタンスを作ってあげればOKです。
該当のViewControllerには、StoryBoard上でStoryboardIDを設定してあげましょう。
(上記のErrorDeruViewControllerIdのところ)

※注意:iOS6以前に対応する場合には、forIndexPathをとっぱらう方法で対応しましょう。そこは仕様上の制限です。

          /~~~~,
          /おしまい /
         /~~~~'
     / ̄ ̄\
    ./   ヽ_   \
   (●)(● )    |
   (__人__)     |
   ヽ`⌒´     |
    {         |
    {       ノ
    ヽ     ノ
   /      ヽ

0 件のコメント:

コメントを投稿