Iphone 为什么这行内存泄漏?

Iphone 为什么这行内存泄漏?,iphone,objective-c,memory-leaks,Iphone,Objective C,Memory Leaks,你知道为什么下面这行会泄露内存吗 cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:person.imageURL]]; 在cellForRowAtIndexPath方法中: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { U

你知道为什么下面这行会泄露内存吗

cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:person.imageURL]];
在cellForRowAtIndexPath方法中:

- (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;
}
这里是person.m的相关方法

- (NSURL*) imageURL
{
    return [NSURL URLWithString:[userInfo valueForKey:@"profile_image_url"]];
}
编辑:添加了初始化方法:

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

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

    return self;
}

这里我能想到的唯一可能导致泄漏的事情是,您可能在person类中保留imageURL,而在其dealloc方法中没有发布。因此,当您释放person时,它正在泄漏imageURL属性。

尝试拆分行并再次测试。它可能会给你一些见解

NSURL *imgURL = person.imageURL;
NSData *imgData = [NSData dataWithContentsOfURL:imgURL]
cell.imageView.image = [UIImage imageWithData: imgData];
您可以对后一种方法进行评论,看看第一种方法是否会导致泄漏


你知道漏洞有多大吗?它是图像大小还是URL大小?

UIImage进行大量缓存。如果UIImage正在缓存图像,则可能会出现泄漏。

您是否有个人的dealloc

当然,这三条管线是泄漏的,如果您不释放,则在dealloc中:

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

这可能与自动释放有关


Cocoa中的构造函数(如
[NSData dataWithContentsOfURL:…])
会自动删除。该调用相当于
[[[NSData alloc]initWithContentsOfURL:…]autorelease]
。这可能与此有关。

我认为您应该在其dealloc中包含[imageURL release]属性保留imageURL,当您释放person类时,它还应该对其保留的属性调用release,这通常发生在dealloc中person类的dealloc方法包含[imageURL release]同样的泄漏还在继续,还有其他建议吗?我的意思是代码看起来还可以,唯一可能是罪魁祸首的方法是initWithUserName,如果你可以在上面发布代码,如果你可以添加initWithUserName,你怎么知道它在泄漏?正如Jason所说;您是如何确定它正在泄漏的?你用的是什么工具?我在仪器上运行,观察是否有泄漏。这就是工具报告的内容。泄漏是32字节,当我将其拆分时,仪器告诉我NSData*imgData=[NSData DATA WITHCONTENTSOFURL:imgURL]是泄漏的来源。我认为32字节的大小对于短URL字符串来说是正确的。也许不知何故person.imageURL被保留,并且从未自动删除。。。选中[imgURL retainCount].NSURL*imgURL=person.imageURL;NSLog(@“保留计数:%i”,[imgURL retainCount]);NSData*imgData=[NSData dataWithContentsOfURL:imgURL];NSLog(@“保留计数:%i”,[imgURL retainCount]);输出是1,然后是9