4

I want to update my TableView from the deprecated initWithFrame:reuseIdentifier:.

My tableview uses custom cells.

Everywhere it says to use initWithStyle:, and that it does not change behavior or the cell in any way from initWithFrame:CGRectZero reuseIdentifier:.

But when I am building with initWithStyle:UITableViewCellStyleDefault reuseIdentifier: the cells become blank (i.e. our custom cell does not work (because it is initialized with some style?)).

After the cell has been initialized (if it did not dequeue), we set texts on the cell. But these are not set when I use initWithStyle:reuseIdentifier: but it works with initWithFrame:CGRectZero. None of the code is changed except for the init method used (initWithStyle).

These rows put in after cell is created (or reused):

cell.newsItemNameLabel.text = @"test";
NSLog(@"NewsItemName: %@",cell.newsItemNameLabel.text);

Results in "NewsItemName: (null)"

Anybody has an idea? What is the real difference between the two?

Thank you

yuji
  • 16,695
  • 4
  • 63
  • 64
Ostmeistro
  • 394
  • 2
  • 15

1 Answers1

3

Your implementation of cellForRowAtIndexPath should look similar to the following:

- (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";

    CustomCell *cell = (CustomCell *)(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell.
    cell.textLabel.text = NSLocalizedString(@"Detail", @"Detail");
    return cell;
}

where CustomCell is the name of your custom cell's class. Note that this implementation uses ARC (Automatic Reference Counting). If you don't happen to use this feature, add a autorelease call to the allocation of your cell.

CustomCell's initWithStyle implementation:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //do things
    }
    return self;
}
fscheidl
  • 2,281
  • 3
  • 19
  • 33
  • Oh! Now I feel silly. When I saw your second edit I realized the method on the CustomCell of course changes too! Thank you so much, I dont have any reputation so I cannot upvote you apparently, but I will psychically send you heaps of love. – Ostmeistro Feb 21 '12 at 16:23
  • I do it exactly as you describe, but the custom cell doesn't get initialized. Can't for the life of me figure out what's wrong. Fscheidl, do you think I can email you my project? – Michael Oct 16 '12 at 10:18
  • Sure, I could look into it - I'm just not comfortable posting my email address online. How would you send me your project? – fscheidl Oct 20 '12 at 17:55