1
votes

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?
}
3

3 Answers

2
votes

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.

1
votes

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?
  }
0
votes

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];
};