Giardino
Giardino

Reputation: 1387

Where can I declare custom initialization for custom table cells?

If I have a custom table cell that is used by:

tableView dequeueReusableCellWithIdentifier

Where inside of that custom cell can I set up custom initialization parameters? The auto-generated .m file for my custom table cell included:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    NSLog(@"INITWITHSTYLE!");
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

I added the NSLog call to see if that initWithStyle is ever called, but that NSLog is never reached, which means that that particular initWithStyle is also never called. So when a custom table cell is initialized using dequeueReusableCellWithIdentifier, which init method of that custom cell is actually used?

Upvotes: 0

Views: 210

Answers (2)

Greg
Greg

Reputation: 25459

If you use storyboard you can use awakeFromNib, otherwise the initWithStyle:reuseIdentifier: should be called

- (void)awakeFromNib {
}

But you should remember that the cell will be reused so let's say if your cell is called first time awakeFromNib is called but later on the cell could be reused and this method won't be called again, it this scenario, if it doesn't work for you, you can use custom setter when you pass the data

//Extended

In comment you asked what method is called when the cell is reused. You can use prepareForReuse, please read discussion (taken from Apple)

- (void)prepareForReuse

Discussion If a UITableViewCell object is reusable—that is, it has a reuse identifier—this method is invoked just before the object is returned from the UITableView method dequeueReusableCellWithIdentifier:. For performance reasons, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state. The table view's delegate in tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell. If the cell object does not have an associated reuse identifier, this method is not called. If you override this method, you must be sure to invoke the superclass implementation.

Upvotes: 0

Cyrille
Cyrille

Reputation: 25144

Your cell will get initialized once in -(void)awakeFromNib (even when it's from a Storyboard).

Then, there's no way to know where it will be dequeued, but it can receive a message when it's removed from screen and enqueued to the reusable cells pool: at this time - (void)prepareForReuse is called.

Upvotes: 1

Related Questions