美文网首页
weakSelf和strongSelf

weakSelf和strongSelf

作者: 骑着雅迪小毛驴上班的老瞿 | 来源:发表于2018-02-05 19:53 被阅读0次

https://www.jianshu.com/p/51bb714051ea

@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。

相关文章

  • RN 调 js 核心代码

    ^{RCTJSCExecutor *strongSelf = weakSelf;if (!strongSelf |...

  • 宏定义

    1.weakSelf和strongSelf

  • iOS宏定义

    1 weakself和strongself #ifndef weakify #if DEBUG #ifhas_fe...

  • weakSelf和strongSelf

    https://www.jianshu.com/p/51bb714051ea 我们发现这样确实解决了问题,但是可能...

  • weakSelf和strongSelf

    在block中常常会用到weakSelf和strong来处理block的产生循环引用的问题。 使用情况 直接在 b...

  • StrongSelf和WeakSelf

    我们在研发的过程中,为了避免循环引用常常会用weak若饮用来打破循环链 但是有时候,在异步多任务的时候,为了避免w...

  • 不一样的书写样式

    **********************1.block中weakSelf 与 strongSelf******...

  • StrongSelf

    weakSelf : 防止循环引用 strongSelf: 防止释放 需要 强引用weakSelf,主要是处理一...

  • weakSelf/strongSelf

    1.Retain Circle的由来 当A对象里面强引用了B对象,B对象又强引用了A对象,这样两者的retainC...

  • weakSelf & strongSelf

    循环引用 循环引用不做过多的解释,两个对象互相持有对方,谁都无法先被释放掉。循环引用经常是由于使用block而引起...

网友评论

      本文标题:weakSelf和strongSelf

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