Do methods called from within a block need to use weakSelf?

谁都会走 提交于 2020-01-01 19:51:10

问题


If the code inside a block calls a method, will a retain cycle exist if that method references self? In other words, does all code downstream of a block need to use the weakSelf/strongSelf pattern?

For example:

__weak __typeof__(self) weakSelf = self;
Myblock block = ^{
    [weakSelf doSomething];
};

. . .

- (void)doSomething
{
    self.myProperty = 5; // Is this ok or does it need to use a weakSelf?
}

回答1:


Retain cycle will be triggered only if you retain self inside the block. Otherwise it will just throw a warning only.

This is fine you can use this. Because block retains every vars used inside, so retain cycle would be like

  1. Self would retain block
  2. If block retains self then
  3. Self would again retain block
  4. block would retain self, so cycle goes on

The thing you are doing in method is just message passing. Everytime block is called a message would be sent to self to doSomething. And you can retain self in doSomething method it wont trigger retain cycle because this method dont have cycle loop to self. Hope you understand :)

  - (void)doSomething
 {
       self.myProperty = 5; // Is this ok or does it need to use a weakSelf?
  }



回答2:


Objective-C is not scoped like you suggest, namely, you don't have access to weakSelf from within -doSomething. Furthermore, as you are calling -doSomething on weakSelf, "self" within that call is actually referring to the same object that weakSelf is.

In short, no, you shouldn't, you can't and you shouldn't.




回答3:


you can do this to get rid of retain cycle problem.

[self class] __weak *weakSelf = self;
self.completionBlock = ^{
    [self class] __strong *strongSelf = weakSelf
    [weakSelf doSomething];
};


来源:https://stackoverflow.com/questions/28651375/do-methods-called-from-within-a-block-need-to-use-weakself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!