2009-09-09 69 views
3

任何想法爲什麼下面的行會泄漏內存?這條線爲什麼會泄漏內存?

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

你怎麼知道它在泄漏?正如傑森所說的那樣, – 2009-09-09 21:36:10

+0

;你怎麼確定它正在泄漏?你使用了什麼工具? – bbum 2009-09-09 22:00:01

+0

我正在儀器上運行它來觀察泄漏。這就是這些工具正在報告的內容。 – Jason 2009-09-10 13:15:01

回答

2

只有我能想到她的事情可能導致泄漏的原因是,您可能會將imageURL保留在您的人員類中,並且在其dealloc方法中沒有發佈版本。所以當你釋放人時,它正在泄漏imageURL屬性。

+0

我的person.h包含 @property(只讀)NSURL * imageURL; – Jason 2009-09-09 18:34:18

+0

和imageURL合成 – Jason 2009-09-09 18:35:30

+0

,我相信你應該在其dealloc中包含一個[imageURL發佈] – Daniel 2009-09-09 18:49:15

1

嘗試拆分線並再次測試。它可能會給你一些見解。

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

你可以評論後者,看看是否第一個導致泄漏。

你知道泄漏有多大嗎?它是圖像大小還是URL大小?

+0

泄漏是32字節,當我把它分開儀器告訴我NSData * imgData = [NSData dataWithContentsOfURL:imgURL]是泄漏的來源。 – Jason 2009-09-10 13:17:27

+0

我在想32字節是適合短URL字符串的大小。也許不知何故,person.imageURL正在保留,從不autoreleases ...檢查[imgURL retainCount]。 – mahboudz 2009-09-11 07:42:40

+0

NSURL * imgURL =人。IMAGEURL; (@「retain count:%i」,[imgURL retainCount]); \t NSData * imgData = [NSData dataWithContentsOfURL:imgURL]; (@「retain count:%i」,[imgURL retainCount]); 輸出是1,然後是9 – Jason 2009-09-11 15:12:45

1

UIImage做了很多緩存。如果UIImage持有圖像的緩存,它可能會泄漏。

1

你有一個人的dealloc?

當然這三條線是泄漏,如果你不是在的dealloc然後釋放:

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

這可能與自動釋放。

Cocoa中的[NSData dataWithContentsOfURL:...]等構造函數會自動自動釋放。該呼叫相當於[[[NSData alloc] initWithContentsOfURL:...] autorelease]。這可能與它有關。