避免在该块中“自我捕获”可能导致保留周期“信息 [英] Avoiding the "capturing self strongly in this block is likely to lead to a retain cycle" message

查看:105
本文介绍了避免在该块中“自我捕获”可能导致保留周期“信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我必须在块中使用全局变量或属性,如下所示:

every time I have to use a global var or property inside a block like this:

self.save = ^(){
  if (isItSaving == NO) {
      [self saveMyFile];
  }
};

我必须重写这样

BOOL *iis = isItSaving;
id myself = self;

self.save = ^(){
  if (iis == NO) {
      [myself saveMyFile];
  }
};

或Xcode会抱怨在这个块中捕获自我可能会导致一个保留周期。

or Xcode will complain "capturing self strongly in this block is likely to lead to a retain cycle...

它甚至会关于BOOL变量吗?

It complains even about BOOL variables?

在块之前重新声明一切似乎是一个无效的解决方案。

Redeclaring everything before a block appears to be a lame solution.

这是正确的方式吗?

这个东西很丑陋ARC。

This stuff is ugly. I am using ARC.

推荐答案

问题只发生在引用 self

在你的情况下你可能访问了一个(布尔)ivar。访问ivar隐式使用 self ,这就是为什么编译器警告你(正确)一个保留周期。

In your case you probably accessed a (boolean) ivar. Accessing the ivar implicitly uses self, that's why the compiler is warning you (correctly) about a retain cycle.

修复保留周期的常见方法是:

The common way to fix the retain cycle is:

typeof(self) __weak weakSelf = self;

self.save = ^() {
    typeof(weakSelf) __strong strongSelf = weakSelf;
    if (strongSelf != nil && ! strongSelf->isItSaving) {
        [strongSelf saveMyFile];
    }
};

...,是的,这是一个丑陋的块的一部分。

... and, yes, that's a bit of an ugly part of blocks.

这篇关于避免在该块中“自我捕获”可能导致保留周期“信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆