美文网首页
weakSelf 需要配合 strong self 使用?

weakSelf 需要配合 strong self 使用?

作者: 一个半吊子工程师 | 来源:发表于2020-08-29 15:40 被阅读0次

一般解决循环引用问题会这么写

self.name = @"Luminous"
__weak typeof(self) weakSelf = self;
[self doSomeBackgroundJob:^{
    __strong typeof(weakSelf) strongSelf = weakSelf;
   NSLog(@"%@",strongSelf.name);
}];

为什么 weakSelf 需要配合 strongSelf 使用呢?

在 block 中先写一个 strongSelf,其实是为了避免在 block 的执行过程中,突然出现 self 被释放的尴尬情况。通常情况下,如果不这么做的话,还是很容易出现一些奇怪的逻辑,甚至闪退。

比如下面这样

self.name = @"Luminous"
__weak typeof(self) weakSelf = self;
[self doSomeBackgroundJob:^{
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"%@",weakSelf.name);
        });
}];
__weak __typeof__(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [weakSelf doSomething];
    [weakSelf doOtherThing];

});

在 doSomething 内,weakSelf 不会被释放.可是在执行完第一个方法后 ,weakSelf可能就已经释放掉,再去执行 doOtherThing,会引起 一些奇怪的逻辑,甚至闪退。
所以需要这么写

self.name = @"Luminous"
__weak typeof(self) weakSelf = self;
[self doSomeBackgroundJob:^{
  __strong typeof(weakSelf) strongSelf = weakSelf;
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"%@",weakSelf.name);
        });
}];
image.png
手动

相关文章

网友评论

      本文标题:weakSelf 需要配合 strong self 使用?

      本文链接:https://www.haomeiwen.com/subject/bifjsktx.html