Jason
Jason

Reputation: 17956

Why is this line leaking memory?

Any ideas why the line below would be leaking memory?

cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:person.imageURL]];

within the cellForRowAtIndexPath method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonCell"];

    if (cell == nil){
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"PersonCell"] autorelease];
    }
    Person *person = [[Person alloc] initWithUserName:[people objectAtIndex:indexPath.row]];

    cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:person.imageURL]];

    cell.textLabel.text = [people objectAtIndex:indexPath.row];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    [person release];

    return cell;
}

And here is the relevant method from person.m

- (NSURL*) imageURL
{
    return [NSURL URLWithString:[userInfo valueForKey:@"profile_image_url"]];
}

EDIT: added init method:

- (id)initWithUserName:(NSString *)user{

    userName = [user copy];
    userInfo = [[TwitterHelper fetchInfoForUsername:userName] retain];  
    updates = [[TwitterHelper fetchTimelineForUsername:userName] retain];

    return self;
}

Upvotes: 3

Views: 877

Answers (5)

Matt Moriarity
Matt Moriarity

Reputation: 697

This may be related to autoreleasing.

Constructors like [NSData dataWithContentsOfURL:...] in Cocoa are automatically autoreleased. That call is the equivalent of [[[NSData alloc] initWithContentsOfURL:...] autorelease]. This may have something to do with it.

Upvotes: 0

Raymond W
Raymond W

Reputation: 555

do you have a dealloc for Person?

Naturally these three lines are a leak if you're not releasing then in dealloc:

userName = [user copy];
userInfo = [[TwitterHelper fetchInfoForUsername:userName] retain];  
updates = [[TwitterHelper fetchTimelineForUsername:userName] retain];

Upvotes: 1

Peter N Lewis
Peter N Lewis

Reputation: 17811

UIImage does a lot of caching. It may be appearing to leak if UIImage is holding a cache of the image.

Upvotes: 1

mahboudz
mahboudz

Reputation: 39376

Try splitting the line and testing again. It might give you some insight.

NSURL *imgURL = person.imageURL;
NSData *imgData = [NSData dataWithContentsOfURL:imgURL]
cell.imageView.image = [UIImage imageWithData: imgData];

And you can comment the latter ones to see if the first one causes leaks.

Do you know how big the leak is? Is it image sized or URL sized?

Upvotes: 1

Daniel
Daniel

Reputation: 22395

Only thing i can think of here that might be causing the leak is that you might be retaining the imageURL in your person class and dont have a release in its dealloc method. So when you are releasing person, it is leaking the imageURL property.

Upvotes: 2

Related Questions