Block外给self加上weak,那不就释放了吗

    xiaoxiao2021-03-25  217

    Apple 官方的建议是,传进 Block 之前,把 self 转换成 __weak 的变量,这样在 Block 中就不会出现对 self 的强引用。但是这样的话, Block 执行完成之前,self 被释放了,weakSelf 也会变为 nil。

    __weak typeof(self) weakSelf = self; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [weakSelf doSomething]; });

    clang 的文档表示,在 doSomething 内,weakSelf 不会被释放。但,下面的情况除外:

    __weak __typeof__(self) weakSelf = self; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [weakSelf doSomething]; [weakSelf doOtherThing]; });

    在 doSomething 中,weakSelf 不会变成 nil,不过在 doSomething 执行完成,调用第二个方法 doOtherThing 的时候,weakSelf 有可能被释放,于是,strongSelf 就派上用场了:

    __weak typeof(self) weakSelf = self; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ __strong typeof(self) strongSelf = weakSelf; [strongSelf doSomething]; [strongSelf doOtherThing]; });

    __strong 确保在 Block 内,strongSelf 不会被释放。

    **总结: 1 在 Block 内如果需要访问 self 的方法、变量,建议使用 weakSelf。 2 如果在 Block 内需要多次 访问 self,则需要使用 strongSelf。** 下面列出block能够拷贝的情况: 1、调用block的copy方法 2、block作为返回值 3、block赋值时 4、Cocoa框架中方法名中含有usingBlock的方法 5、GCD中

    关于GCD中block再提一点: GCD中的block并没有直接或间接被self强引用的,所以不会存在循环引用,故不需要weakSelf;又GCD中block能够自动copy,所以self超出作用域仍可用,故不需要写strongSelf

    总结: weakSelf是为了解决循环引用 strongSelf是为了保证任何情况下self在超出作用域后仍能够使用

    参考链接:http://www.jianshu.com/p/36342264d6df

    转载请注明原文地址: https://ju.6miu.com/read-190.html

    最新回复(0)