Using alloc and init when using a UITableViewCell from Storyboard

流过昼夜 提交于 2020-01-04 15:58:48

问题


I'm doing a simples app using Storyboard that a have a View with a UITableView with a UITableViewCell that do the navigation to another UIView.

So a have to code to populate the cell on the table view.

- (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;
}

I realised that the code if (cell == nil) { ... never executes so I really need to do that on uses the cell from Storyboard?

Thanks.


回答1:


You are correct; that code is guaranteed to return a non-nil cell if you are using a storyboard. Also, in iOS 6, the new call dequeueReusableCellWithIdentifier:forIndexPath: never returns nil. See the discussion in my book:

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




回答2:


If you've declared your UITableViewCell in table view's prototype cells it's already allocated and just needs to be dequeued. If you're using a custom UITableViewCell subclass, then you must check if it's nil and allocate new entities when necessary.




回答3:


Nope you don't need that code when using a cell made in your storyboard.

It is probably best to remove this code so that you crash nice and early if the identifier you gave to the cell in interface builder and the identifier you use in code ever drift. This snippet will mask this error and just provide a cell that you most likely was not intending to have.



来源:https://stackoverflow.com/questions/14865266/using-alloc-and-init-when-using-a-uitableviewcell-from-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!