Block will be retained by an object strongly retained by the captured object

Block will be retained by an object strongly retained by the captured object

防止iOS中私有属性在block中的循环引用

对于一般的@property修饰的属性我们可以使用__weak转换一下self来修饰

    __weak typeof(self) weakSelf = self;
    //然后把self.xxx变成weakself.xxx

那么.对于一些没有使用@property修饰的私有属性呢.比如一下这种.

    @interface xxx () {
        NSString *yyy;
    }
    // MARK: 1
    //Block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior
    //Insert 'self->'
    self.button.didSelectBlock = ^{
        yyy = @"123131133";
        NSLog(@"%@",yyy);
    };

编译器让我们使用self->去修饰这个属性,
当我们换成self->的时候

    // MARK: 2
    //Block will be retained by an object strongly retained by the captured object
    self.button.didSelectBlock = ^{
        self->yyy = @"12313123";
        NSLog(@"%@",self->yyy);
    };

循环引用了.那么我们如果把self替换成weakSelf呢

    // MARK: 3
    // ERROR
    //Dereferencing a __weak pointer is not allowed due to possible null value caused by race condition, assign it to strong variable first
    __weak typeof(self) weakSelf = self;
        self.button.didSelectBlock = ^{
        weakSelf->yyy = @"12313123";
        NSLog(@"%@",weakSelf->yyy);
    };
    // MARK: 4
    __weak typeof(self) weakSelf = self;
    self.button.didSelectBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->yyy = @"12313123";
        NSLog(@"%@",strongSelf->yyy);
    };
早起的年轻人 CSDN认证博客专家 移动开发 项目管理 Java
只要用心去做,每一件事情还是有可能成功的,当然成功是没有界限的,只不过是达到自己心里的那个目标,公众号:我的大前端生涯,一个爱喝茶的程序员,通常会搞搞SpringBoot 、Herbinate、Mybatiys、Android、iOS、Flutter、Vue、小程序等.
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:设计师小姐姐 返回首页