简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM