Nitin Malguri
Nitin Malguri

Reputation: 201

Instrument show memory leak on [NSBundle mainBundle] loadNibNamed

Friends,

I run my code in instruments, it show memory leak in 5 line(out of following code) i.e cell = [[[NSBundle mainBundle] loadNibNamed:@"ZoomCustomVideoCell" owner:self options:nil] objectAtIndex:0];

I have no idea why it shows a memory leak there and what is solution for same

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

    static NSString *CellIdentifier = @"ZoomCustomVideoCell";

    ZoomCustomVideoCell *cell = (ZoomCustomVideoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ZoomCustomVideoCell" owner:self options:nil] objectAtIndex:0];

        cell.m_zoomMsg = [[[ZoomMessage alloc] init] autorelease];
        [[cell m_zoomMsg] initWithJSON:[m_tmpVideoList objectAtIndex: indexPath.row]];
        [[cell videoLabel] setText:[cell.m_zoomMsg _from]];
        [[cell m_labelLocation] setText:[NSString stringWithFormat:@"%@", cell.m_zoomMsg._location]];
        [[cell videoLabelB] setText:[cell.m_zoomMsg _uploadDesc]];
        NSLog(@"UserName: %@", [[cell videoLabel] text]);

        [cell refreshImage];

    }

    return cell;
}

Upvotes: 2

Views: 4427

Answers (2)

dreamlax
dreamlax

Reputation: 95335

The loadNibNamed:owner:options: method takes the argument passed as owner: as the “File's Owner” of the nib. This means that outlets in the nib will be connected to whatever you pass as the owner. Since you are passing self as the owner, it will be overwriting any previously assigned outlets for self with ones from the newly loaded nib. To establish outlet connections, the nib loader uses setValue:forKey: on the provided owner. If you have set up your outlets as properties with the correct memory management, then there should be no leak. If you only have your outlets as instance variables then (it is unclear but I am assuming) that the objects are retained automatically as they are set.

There are two solutions here:

  1. Provide proper memory management for your outlets, e.g. turn them into properties if they aren't already and ensure that they have the correct memory management attributes.

  2. Provide a different owner to the loadNibNamed:owner:options: method, one that doesn't already have any outlets established and one that you know will handle the outlets appropriately.

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107141

This line causes the memory leak:

cell = [[[NSBundle mainBundle] loadNibNamed:@"ZoomCustomVideoCell" owner:self options:nil] objectAtIndex:0];

change it to:

cell = [[[[NSBundle mainBundle] loadNibNamed:@"ZoomCustomVideoCell" owner:self options:nil] objectAtIndex:0] autorelease];

Upvotes: 0

Related Questions