嵌套块和对自身的引用



>我有一个块,我在其中使用self所以我声明了一个对self的弱引用:

__weak MyClass *weakSelf = self;

现在我的问题:

  1. 我在定义weakSelf时收到一个错误,我不明白这应该是什么意思。

    不能在自动变量上指定弱属性

  2. 在我的块内,我weakSelf传递到另一个块,我不确定我现在是否必须像这样再次做同样的事情:

    __weak MyClass *weakWeakSelf = weakSelf;
    

    然后把weakWeakSelf传给那个街区?

这很可能发生在您瞄准iOS 4时。您应该将其更改为

__unsafe_unretained MyClass *weakWeakSelf = weakSelf;

with ARC

__weak __typeof__(self) wself = self;

无电弧

__unsafe_unretained __typeof__(self) wself = self;

使用 libextobjc,它将是可读且简单的:

- (void)doStuff
{
    @weakify(self); 
    // __weak __typeof__(self) self_weak_ = self;
    [self doSomeAsyncStuff:^{
        @strongify(self);
        // __strong __typeof__(self) self = self_weak_;
        // now you don't run the risk of self being deallocated
        // whilst doing stuff inside this block 
        // But there's a chance that self was already deallocated, so
        // you could want to check if self == nil
        [self doSomeAwesomeStuff];
        [self doSomeOtherAsyncStuff:^{
            @strongify(self);
            // __strong __typeof__(self) self = self_weak_;
            // now you don't run the risk of self being deallocated
            // whilst doing stuff inside this block 
            // Again, there's a chance that self was already deallocated, so
            // you could want to check if self == nil
            [self doSomeAwesomeStuff];
        }];
    }];
}

相关内容

  • 没有找到相关文章

最新更新