objective-c - 为什么iOS的Masonry中的self不会循环引用?
大家讲道理
大家讲道理 2017-04-17 17:26:06
0
2
880
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的bk_addEventHandler方法, 其中使用strong self, 该viewController就无法dealloc, 我理解是因为,self retain self.view, retain testButton, retain self.
但是如果只用Mansonry的mas_makeConstraints方法, 同样使用strong self, 该viewController却能正常dealloc, 请问这是为什么, 为什么Masonry没有导致循环引用

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
Ty80

Whether it will cause a circular reference, you only need to check whether the block is copied inside the function.
Like Mansonry

  • (NSArray )mas_makeConstraints:(void(^)(MASConstraintMaker ))block {
    self.translatesAutoresizingMaskIntoConstraints = NO;
    MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self];
    block (constraintMaker);
    return [constraintMaker install];
    }

If there is no copy and it is released after use, it will not cause a circular reference.

黄舟

Isn’t it warning when there is a possibility of circular reference?
This is the change

    __weak id weakSelf = self;
    [testButton bk_addEventHandler:^(id sender) {
        __strong <#你的VC类#> strongSelf = weakSelf;
        [strongSelf dismissViewControllerAnimated:YES completion:nil];
    } forControlEvents:UIControlEventTouchUpInside];

Circular references can be avoided. Don’t ask me why, I don’t quite understand it, it’s just that everyone writes it like this.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template