在我的应用程序中,我选择了一个表格视图控制器,该控制器的每个单元格中都带有UIImageView,并加载了一些本 map 像文件。但是问题是当按下导航栏中的后退按钮时,分配给“图像视图”的内存没有释放,并导致内存泄漏:

这是我在表视图中来回查询时的内存日志:

这是导致我正在谈论的表视图控制器的prepareForSegue:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.

    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];

    if (indexPath) {
        if (indexPath.section == 0) {
            //a section is selected

            if ([segue.destinationViewController isKindOfClass:[SectionTableViewController class]]) {
                 NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"s%ld", (long)indexPath.row + 1] ofType:@"json"];
                 NSData *data = [NSData dataWithContentsOfFile:jsonFilePath];
                 NSDictionary *sectionData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                 SectionTableViewController *stvc = (SectionTableViewController *)segue.destinationViewController;
                 stvc.firstPrb = [sectionData objectForKey:@"firstPrb"];
                 stvc.lastPrb = [sectionData objectForKey:@"lastPrb"];
                 stvc.sectionTitle = [sectionData objectForKey:@"sectionTitle"];
            }
        }
    }
    }

这是用于在提到的表视图控制器中生成单元格的代码:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProverbCell" forIndexPath:indexPath];

    // Configure the cell...
    NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%ld", self.firstProverb.intValue + indexPath.row] ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:jsonFilePath];
    NSDictionary *proverbData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    cell.textLabel.text = [proverbData objectForKey:@"proverb"];
    @autoreleasepool {
    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg", self.firstProverb.intValue + indexPath.row]];
    }

    return cell;
    }

现在的问题是:单击后退按钮后不应该释放内存吗?没有指向图像视图或其他任何东西的强大指针...

最佳答案

[UIImage imageNamed:]将缓存UIImage,如果不需要缓存,请使用[UIImage imageWithContentsOfFile:]

您还可以自己使用NSMutableDictionary缓存UIImage,然后在属性时释放NSMutableDictionary

关于ios - 单击返回按钮后未释放UITableViewCell的UIImage的内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25216153/

10-14 21:14
查看更多