简体   繁体   中英

Memory leak in UIImage's imageWithContentsOfFile

I have a table view with 10 cells displaying an image. Everytime I scroll, the app allocates more memory (but doesn't show this in leaks) but in allocations, I can see that memory increases by like 2 megabytes with each scroll.

This is the code which leaks, specifically the line where i set the imageview's image (if I comment it out, it doesn't leak):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"background_stripes" ofType:@"png"]];
    return cell;
}

在此处输入图片说明

UPDATE: I created a simple new project with 1 view controller:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 130.f;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 16;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"background_stripes" ofType:@"png"]];


    return cell;
}

Very simple...I don't see any problem here...but leaks when I scroll, the memory consumption grows over time...

I had the same problem with dataWithContentsOfURL: solved it by @autoreleasepool

Try this:

@autoreleasepool {
     self.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"background_stripes" ofType:@"png"]];
}

The problem is that there is no leaks =). The top graph illustrates the allocations and not leaks. Leaks are in the bottom graphics and their graph is red, so there is NO memory leaks. You'd probably thought that "Overall Bytes" stands for memory leaks but it's not, it's just the number of bytes that program allocated during runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM