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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18683985/article/details/82592099

想看答案可以直接瞅瞅底下代码.

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

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

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

    @interface xxx () {
        NSString *yyy;
    }

我们不做任何处理直接在block中使用

    // 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);
    };

好吧,直接报错了.这里需要使用一个strong类型的.
最后,在Block里头使用__strong转一下weakSelf就OK了

    // MARK: 4
    __weak typeof(self) weakSelf = self;
    self.button.didSelectBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->yyy = @"12313123";
        NSLog(@"%@",strongSelf->yyy);
    };

猜你喜欢

转载自blog.csdn.net/qq_18683985/article/details/82592099