OStack程序员社区-中国程序员成长平台

标题: ios - 没有保留周期,但为什么仍然收到保留周期警告? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 16:51
标题: ios - 没有保留周期,但为什么仍然收到保留周期警告?

我正在尝试使用 AFNetworking2.6.3 的 UIImageView 扩展从远程服务器获取图像。一切正常,图像已返回并成功渲染。但我在 Xcode7.3.1 中收到保留周期警告:在此 block 中强烈捕获“单元格”可能会导致保留周期

-(UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier"cell"];
    if(self.dataSourceModel) {
        Model *model = self.dataSourceModel.items[indexPath.row];
        NSURL *url = [NSURL URLWithString:model.imageURL];
        NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
        UIImage *placeholderImage = [UIImage imageNamed"placeholder"];

        //I don't use __weak cell in the block
        [cell.imageView setImageWithURLRequest:theRequest placeholderImage:placeholderImage success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
            cell.imageView.image = image; //get warning at this line
            [cell setNeedsLayout];
        } failure:nil];
    }
    return cell;
}

我可以看到,由于单元实例已在 block 中捕获,因此 block 具有单元实例的所有权(以及 cell.imageView)。如果保留周期确实存在,则单元格或 imageView 应该拥有 block 的所有权。

但我已经查看了 UIImageView+AFNetworking.hUIImageView+AFNetworking.m源代码, UIImageView 没有任何 block 的属性。该 block 只是方法的参数,而不是实例变量。 UITableViewCell 也不拥有 block 的所有权。

我什至用 Leaks 查了一下,Leaks 也没有报错。

所以我相信这里没有保留周期,但为什么我仍然在这里收到 Xcode 警告?如果我使用 __weak cell__weak UITableViewCell *weakCell = cell;,警告就会消失。但我还是想知道:

任何提示都会有所帮助,非常感谢。



Best Answer-推荐答案


当然没有保留周期,您可以通过省略完成 block 中的代码来避免警告。看一下 AFNetworking imageView 子类(第 152 行),setImage... 的高潮是设置 ImageView 的图像。您的代码需要重新设置它,或更改布局状态。

应该也不需要 if (self.dataSourceModel)。如果数据源构建正确,我们已经回答了 tableView:numberOfRowsInSection: 中的行数,并且当模型为空时该答案为零,避免调用 cellForRow... 完全一致。

关于ios - 没有保留周期,但为什么仍然收到保留周期警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37547448/






欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) Powered by Discuz! X3.4