5

Can doFirst cause a retain cycle here?

@interface Example : NSObject
@property (nonatomic, strong) void (^block)();
@end

@implementation Example

- (void)doFirst
{
    __weak id weakSelf = self;
    self.block = ^ {            
        [weakSelf doSecond];
    };

    self.block();
}

- (void)doSecond
{
    self.value = //...
    // do other stuff involving self
}
@end
JRG-Developer
  • 12,454
  • 8
  • 55
  • 81
  • A useful tip when referencing to a weakSelf is to do something like this: `__weak typeof (self) weakSelf = self`. Makes things easier when reusing code in different places etc – liamnichols Feb 20 '14 at 13:49

2 Answers2

5

Unlike blocks, methods are not objects; they cannot hold a permanent reference to objects.

Your code would not cause a retain cycle. The fact that the code inside doSecond references self explicitly does not mean that self would get retained an extra time. When your block calls doSecond, its self comes from the weakSelf reference inside doFirst.

Note: When you store blocks as properties, use (nonatomic, copy) instead of (nonatomic, strong).

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Why would `copy` vs `strong` matter here? It's created and owned by `Example` class, not provided by another class. AFAIK, wouldn't that just add extra overhead when creating the block? – JRG-Developer Feb 20 '14 at 13:43
  • Regardless of `copy` vs `strong` semantics, this is a clear answer and makes a lot of sense, especially regarding `methods are not objects`. +1. Thanks. – JRG-Developer Feb 20 '14 at 13:48
  • 1
    @JRG-Developer You need a copy for blocks created on the stack. In the code that you show it does not matter, because you call the block before exiting from the method in which it is defined. However, if you would like the block to stay around, you need to make a copy of it before method exits. – Sergey Kalinichenko Feb 20 '14 at 13:49
0

No It won't. Because It just point to method which won't hold whatwhere inside methods which just an reference as like object.

Mani
  • 17,549
  • 13
  • 79
  • 100