简体   繁体   English

Objective-C ARC区块__strong __weak

[英]Objective-C ARC block __strong __weak

With ARC 使用ARC

test1: 测试1:

@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. object( self )具有对该块的显式强引用。 And the block has an implicit strong reference to self . 并且该块对self具有隐式的strong引用。 That's a cycle, and now neither object will be deallocated properly. 这是一个周期,现在两个对象都不会被正确释放。

so test1 dealloc not calling. 所以test1 dealloc不调用。

test2: 测试2:

@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 . __weakSelf-> __strongSelf,我认为与test1没什么区别,但是test2可以调用dealloc

Why? 为什么?

Have a look at this answer: https://stackoverflow.com/a/28475562/543224 看看这个答案: 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. 它确实确保执行块时不会释放self。 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 ). 在第一种情况下,该块捕获变量self ,这是一个强引用(即,其类型为test01ViewController * __strong )。

In the second case, the block captures the variable weakSelf , which is a weak reference (ie it has type test03ViewController * __weak ). 在第二种情况下,该块捕获了变量weakSelf ,它是一个弱引用(即,其类型为test03ViewController * __weak )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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