开发者

UITableView with images not releasing resources

I have a UITableView where each cell is an image. Only one cell is visible at a time. The images are loaded on demand. The user scrolls to a cell and its image loads.

Thi is my cellForRowAtIndexPath method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

if (cell == nil) {
    // this is being compiled for OS 2.0, this is why I am using initWithFrame… it is working fine on 3.0 iPhone.
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 480, 320) reuseIdentifier:MyIdentifier] autorelease];
}

UIImage *imagemX;
UIImageView *myView;

imagemX = [[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle] 
pathForResource:[NSString stringWithFormat: @"img%d", (indexPath.row+1)] ofType:@"jpg"]] autorelease];

myView = [[[UIImageView alloc]initWithImage:imagemX] autorelease];

[cell addSubview: myView];

return cell;
}

The problem with this code is that the memory use always inc开发者_如何学JAVAreases as I scroll thru the table, even if I go back to images previously shown. After scrolling a little bit, the application crashes, probably kicked by springboard by excessive use of memory.

Am I missing something? How can I force an image to release its resources when it is not visible?


You're adding subviews to the cell every time they request a cell, but you never remove them. You need to remove the old subview first. As your code stands, every time a cell is redisplayed it will get another UIImageView layered onto it.

Personally, I'd recommend making a UITableViewCell subclass with the UIImageView as a property, and then calling [cell setImageView:]. If that won't work, then make sure you remove the old subview before adding the new one.


don't know the exact reason to this problem but is there a method that you need to implement which will be fired when a cell goes out of range? In here maybe you could release the subview/image/etc?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜