Alex Alex - 2 months ago 14
iOS Question

Returning 'self' while it is not set to the result of '[(super or self) init...]' when I initialize custom cell

In CustomCell.m I define init method where I want to load cell from the IB:

- (id)init {
self = [super init];
if (self) {
NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
self = [nib objectAtIndex:0];

}
return self;
}


In the MyTableViewController.m in the method cellForRowAtIndexPath I initialize my custom cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

cell=[[CustomCell alloc]init];
return cell;


}

Everything works as I expected but when I did
Product -> Analyse
I get

Returning 'self' while it is not set to the result of '[(super or self) init...]'


What am I doing wrong?

Answer

You are overwriting self (returned from super init) with the object returned from your array. If you want to load a custom cell from a nib, do it in your cellForRowAtIndexPath method, or create a convenience class method on your custom cell that loads from the nib:

In your cellForRowAtIndexPath:

cell = [CustomCell cell];

In your cell's implementation:

+(CustomCell*)cell
{
    NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];         
    return [nib objectAtIndex:0];
}

EDIT - changed method name since new* indicates that a retained object will be returned.