weijia.wang
weijia.wang

Reputation: 2168

Objective-C ARC block __strong __weak

With ARC

test1:

@interface test01ViewController ()

@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);

@end

@implementation test01ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"test01";

    [self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
        [self doSomethingWithObj:obj];
    }];
}

object (self) has an explicit strong reference to the block. And the block has an implicit strong reference to self. That's a cycle, and now neither object will be deallocated properly.

so test1 dealloc not calling.

test2:

@interface test03ViewController ()

@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);

@end

@implementation test03ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.navigationItem.title = @"test03";

    __weak test03ViewController *weakSelf = self;
    [self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
        __strong test03ViewController *strongSelf = weakSelf;
        [strongSelf doSomethingWithObj:obj];
    }];
} 

__weakSelf - > __strongSelf, I think it not difference with test1 , but test2 can calling dealloc.

Why?

Upvotes: 0

Views: 1294

Answers (2)

rodskagg
rodskagg

Reputation: 3937

Have a look at this answer: https://stackoverflow.com/a/28475562/543224

Anyway regarding this pattern, capturing a strong reference there doesn't do anything for the case of self getting deallocated before the block runs, that can still happen. It does ensure self doesn't get deallocated while executing the block. This matters if the block does async operations itself giving a window for that to happen.

Upvotes: 2

newacct
newacct

Reputation: 122499

In the first case, the block captures the variable self, which is a strong reference (i.e. it has type test01ViewController * __strong).

In the second case, the block captures the variable weakSelf, which is a weak reference (i.e. it has type test03ViewController * __weak).

Upvotes: 0

Related Questions