简体   繁体   中英

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;
}

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.

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?

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

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];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM