在Storyboard中使用UITableViewCell时使用alloc和init

Gre*_*reg 2 objective-c storyboard uitableview ios

我正在使用一个故事板应用simples一个有一个视图UITableViewUITableViewCell那些导航到另一个UIView.

所以必须编写代码来填充表视图上的单元格.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"SampleCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        NSLog(@"cai no init da cell");
    }

    GPItem *item = [self.items objectAtIndex:indexPath.row];

    cell.textLabel.text = @"Post";
    cell.detailTextLabel.text = item.imageURL;

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

我意识到代码if (cell == nil) { ...永远不会执行所以我真的需要这样做才能使用Storyboard中的单元格吗?

谢谢.

mat*_*att 5

你是对的; 如果您使用的是故事板,则可以保证该代码返回非零单元格.此外,在iOS 6中,新调用dequeueReusableCellWithIdentifier:forIndexPath: 永远不会返回nil.请参阅我的书中的讨论:

http://www.apeth.com/iOSBook/ch21.html#_registering_a_cell_class