Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

为啥你的block里面不见你用weakSelf来防止循环引用,怎么做到的啊 #15

Open
HJC1990 opened this issue Jul 11, 2018 · 6 comments

Comments

@HJC1990
Copy link

HJC1990 commented Jul 11, 2018

No description provided.

@RondaHo
Copy link

RondaHo commented Jul 11, 2018

如果block里面持有的变量,又持有这个block本身,才会造成循环引用。不一定每一个block里面都需要weakself来修饰。具体要看你说的是那段代码

@HJC1990
Copy link
Author

HJC1990 commented Jul 11, 2018

  • (void)requestDidFinish
    {
    _state = TYRequestStateFinish;

    void (^finishBlock)() = ^{
    if ([_delegate respondsToSelector:@selector(requestDidFinish:)]) {
    [_delegate requestDidFinish:self];
    }

      if (_successBlock) {
          _successBlock(self);
      }
      
      if (_embedAccesory && [_embedAccesory respondsToSelector:@selector(requestDidFinish:)]) {
          [_embedAccesory requestDidFinish:self];
      }
    

    };

    if (_asynCompleteQueue) {
    finishBlock();
    }else {
    dispatch_async(dispatch_get_main_queue(),finishBlock);
    }
    }

@RondaHo
Copy link

RondaHo commented Jul 11, 2018

你是说这段代码,block里面没有写weakself么:

void (^finishBlock)() = ^{
if ([_delegate respondsToSelector:@selector(requestDidFinish:)]) {
    [_delegate requestDidFinish:self];
}

如果是,这里finishBlock里面使用了self,但是self并没有持有finishBlock。finishBlock不是self的属性或成员变量。没有构成相互持有关系,不会造成循环引用

@HJC1990
Copy link
Author

HJC1990 commented Jul 11, 2018

对 但是我这样写的话,xcode会有黄色警告说block implictly retains'self'

@RondaHo
Copy link

RondaHo commented Jul 11, 2018

这种警告是Xcode的一种预防性警告。不是一定表示已经构成循环引用。这警告意思是block中使用了self的实例变量_delegate,因此block会隐式的retain住self。Xcode认为这可能会给开发者造成困惑,或者因此而造成循环引用,所以警告我们要现式的在block中使用self,以达到block现式retain住self的目的。
可以在Build Setting里面搜索Implicit retain of 'self' within blocks,将YES设置为NO即可屏蔽此类警告
一般这种警告才是循环引用警告:
Capturing self in this block is likely to lead to a retain cycle

@HJC1990
Copy link
Author

HJC1990 commented Jul 11, 2018

是这样的,是我理解错了,错以为是循环引用问题并估计是作者是用什么方法优化了,谢啦

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants