簡體   English   中英

為什么這條線會泄漏內存?

[英]Why is this line leaking memory?

任何想法為什么下面的行會泄漏內存?

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

編輯:添加init方法:

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

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

    return self;
}

我能想到的唯一可能導致泄漏的是你可能會在你的人類中保留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] 這可能與它有關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM