Nested blocks and references to self

℡╲_俬逩灬. 提交于 2019-12-21 04:50:21

问题


I have a block wherein I use self so I declare a weak reference to self:

__weak MyClass *weakSelf = self;

Now my questions:

  1. I get an error where I define weakSelf and I don't understand what this should mean.:

    weak attribute can not be specified on an automatic variable

  2. Inside my block I pass weakSelf to another block and I am not sure if I now have to do the same thing again like so:

    __weak MyClass *weakWeakSelf = weakSelf;
    

    And then pass weakWeakSelf to that block?


回答1:


This is most likely occurring as you are targeting down to iOS 4. You should change it to be

__unsafe_unretained MyClass *weakWeakSelf = weakSelf;



回答2:


With ARC

__weak __typeof__(self) wself = self;

Wihtout ARC

__unsafe_unretained __typeof__(self) wself = self;



回答3:


With libextobjc it will be readable and easy:

- (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];

        }];
    }];
}


来源:https://stackoverflow.com/questions/10431110/nested-blocks-and-references-to-self

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!