繁体   English   中英

我什么时候应该在块中使用弱势,为什么砌体中没有保留周期?

[英]When should I use weakself in a block, and why there is no retain cycle in Masonry?

UIButton *testButton = [[UIButton alloc] init];
[self.view addSubview:testButton];
testButton.backgroundColor = [UIColor redColor];
[testButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.equalTo(@100);
    make.height.equalTo(@100);
    make.left.equalTo(self.view.mas_left);
    make.top.equalTo(self.view.mas_top);
}];
[testButton bk_addEventHandler:^(id sender) {
    [self dismissViewControllerAnimated:YES completion:nil];
} forControlEvents:UIControlEventTouchUpInside];

我在代码中同时使用了BlocksKit和Masonry。 如果使用I BlocksKit, bk_addEventHandler ,则存在一个保留周期,我认为这是因为self保留self.view,保留testButton,保留self。 但是,当我单独使用Mansonry而不使用BlocksKit时,并且在Masonry mas_makeConstraints使用了强自我时,我发现没有保留周期,因为viewController可以调用dealloc方法。 谁能向我解释砌筑中没有保留周期吗?

这是因为块套件块被保留以便以后执行(因此,通过对self的引用,即保持周期 ),而砌体块现在或多或少被执行,然后被丢弃。

同样,调用UIView animate...方法时,您不必担心保留周期。 这是因为一旦代码结束,运行循环就会结束,动画块将被执行并丢弃。 但是,在NSNotification观察程序块中对self的引用可能会导致保留周期,因为它只是被系统永久保留,直到您取消注册该通知为止,同时还要保留该观察程序。

暂无
暂无

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

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