Block中strongSelf的使用

作者: 小胡子杰克 | 来源:发表于2016-12-05 16:23 被阅读40次

Block中strongSelf的使用

1.weakSelf与其缺陷

//ClassB是一个UIViewController,假设从ClassA pushViewController将ClassB展示出来
@interface ClassB ()
@property (nonatomic, copy) dispatch_block_t block;
@property (nonatomic, strong) NSString *str;
@end
@implementation ClassB
- (void)dealloc {}
- (void)viewDidLoad { [super viewDidLoad]; 
    self.str = @"111"; 
    __weak typeof(self) weakSelf = self; 
    self.block = ^{ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), 
    dispatch_get_main_queue(), ^{ 
      NSLog(@"%@", weakSelf.str); 
  }); 
 }; 
  self.block(); }

这里会有两种情况:

  • 若从A push到B,10s之内没有pop回A的话,B中block会执行打印出来111。
  • 若从A push到B,10s之内pop回A的话,B会立即执行dealloc,从而导致B中block打印出(null)。
    这种情况就是使用weakSelf的缺陷,可能会导致内存提前回收。

2.weakSelf和strongSelf

@interface ClassB ()
@property (nonatomic, copy) dispatch_block_t block;
@property (nonatomic, strong) NSString *str;
@end
@implementation ClassB
- (void)dealloc {}
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.str = @"111"; 
    __weak typeof(self) weakSelf = self; 
    self.block = ^{ 
    __strong typeof(self) strongSelf = weakSelf; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), 
    dispatch_get_main_queue(), ^{ 
      NSLog(@"%@", strongSelf.str); 
    }); 
}; 
self.block(); }

我们发现这样确实解决了问题,但是可能会有两个不理解的点。

  • 这么做和直接用self有什么区别,为什么不会有循环引用:外部的weakSelf是为了打破环,从而使得没有循环引用,而内部的strongSelf仅仅是个局部变量,存在栈中,会在block执行结束后回收,不会再造成循环引用。
  • 这么做和使用weakSelf有什么区别:唯一的区别就是多了一个strongSelf,而这里的strongSelf会使ClassB的对象引用计数+1,使得ClassB pop到A的时候,并不会执行dealloc,因为引用计数还不为0,strongSelf仍持有ClassB,而在block执行完,局部的strongSelf才会回收,此时ClassB dealloc。

From:简书:羊谈循环引用

相关文章

网友评论

    本文标题:Block中strongSelf的使用

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