在我的应用程序中,我转到一个 TableView Controller ,每个单元格中都有一个UIImageView
,并加载了一些本地图像文件。但问题是当按下导航栏中的后退按钮时,为 ImageView 分配的内存未释放并导致内存泄漏:
这是我来回切换到我的 TableView 时的内存日志:
这是通向我正在谈论的 TableView Controller 的 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"];
}
}
}
}
这是在上述 TableView Controller 中生成单元格的代码:
- (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;
}
现在的问题是:点击后退按钮后,内存不应该被释放吗?!没有指向 ImageView 或其他任何内容的强指针...
最佳答案
[UIImage imageNamed:]
将缓存 UIImage,如果您不需要缓存它,请使用 [UIImage imageWithContentsOfFile:]
。
您也可以使用 NSMutableDictionary
自己缓存 UIImage,然后在属性时释放 NSMutableDictionary
。
关于ios - UITableViewCell 的 UIImage 的内存在 segue 后退按钮后未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25216153/