2009-09-09 71 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]。这可能与它有关。