您的位置:首页 > 其它

block 中 weakSelf/strongSelf 大法

2015-08-03 08:54 567 查看
在学习AFNetWorking的过程中,经常看到类似:

[code]//__weak __typeof(self)weakSelf = self; 
//然后在block中,看到:
//__strong __typeof(weakSelf)strongSelf = weakSelf;
//如下边代码:
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
    [self.lock lock];
    if (!self.backgroundTaskIdentifier) {
        UIApplication *application = [UIApplication sharedApplication];
        __weak __typeof(self)weakSelf = self;
        self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
            __strong __typeof(weakSelf)strongSelf = weakSelf;

            if (handler) {
                handler();
            }

            if (strongSelf) {
                [strongSelf cancel];

                [application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
                strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
            }
        }];
    }
    [self.lock unlock];
}


这是因为:没有添加__strong 引用的话,编译器会有警告,为什么会警告呢,因为弱引用的weakself会在某个时间被释放,有可能是在执行之后的block之前就会被释放,这样在后续的操作操作就有可能出错,所以最好是添加一个对weakSelf__strong引用。

参考:

1 http://stackoverflow.com/questions/11899134/how-to-properly-address-weak-receiver-may-be-unpredictably-null-in-arc-mode


2 http://stackoverflow.com/questions/19018456/ios-blocks-and-strong-weak-references-to-self

原文点这里——–
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: