Alexey
Alexey

Reputation: 7257

Custom cell memory leak with ARC enabled

Why do I have a memory leaking with ARC enabled(highlighted in bold)?

I have CustomCell.m

   +(CustomCell*)cell
{


    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"CustomCell_iPhone" owner:self options:nil];         
        return [nib objectAtIndex:0];

    } else {
        NSArray *nib =[[NSBundle mainBundle] loadNibNamed:@"CustomCell_iPad" owner:self options:nil];          **//leaking 100%**  
        return [nib objectAtIndex:0];

    }
}

In my tableview conteroller:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell=[CustomCell cell]; **// 100% leaking**
...
}

Upvotes: 0

Views: 1158

Answers (1)

jmstone617
jmstone617

Reputation: 5707

So, two things. One, I gather you're creating this cell in a .xib file. Set the reuse identifier on the cell in IB. Then, instead of this CustomCell class method, unload the nib in tableView:cellForRowAtIndexPath:, like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Assuming you set a reuse identifier "cellId" in the nib for your table view cell...
    MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (!cell) {
        // If you didn't get a valid cell reference back, unload a cell from the nib
        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:nil options:nil];
        for (id obj in nibArray) {
            if ([obj isMemberOfClass:[MyCell class]]) {
                // Assign cell to obj, and add a target action for the checkmark
                cell = (MyCell *)obj;
                break;
            }
        }
     }

     return cell;
}

The second thing is that by trying to dequeue a reusable cell first, you will get much much better performance.

Upvotes: 1

Related Questions