天天看点

使用 __weak typeof(self) weakSelf = self 在代码块内部崩溃问题

今天做一个初始化数据后刷新某个界面数据功能,

在代码块使用__weak typeof(self) weakSelf = self 放在代码块外部,内部使用[weakSelf test] 方法 调用 ;

但是,由于这部分代码块使用计时器循环调用,所以当我前面几个方法执行完了之后 [weakSelf test]  方法 weakself 会 为  nil

网上查了一下

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

在学习AFNetWorking的过程中,经常看到类似:

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

}

参考文章:AFNetWorking 学习