Timer强引用问题与循环引用

Timer强引用

假设VC有一个timer正在执行,如果不调用[self.timer invalidate];,当我们pop回去的时候timer还会一直执行并且VC的dealloc不会调用,也就是VC一直没有析构

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(fireHome) userInfo:nil repeats:YES];

为什么timer没有释放,来看下官方文档

//The object to which to send the message specified by aSelector when the timer fires. 
//The timer maintains a strong reference to this object until it (the timer) is invalidated.
//当timer fire的时候会对`target`进行强持有,直到调用 `invalidated`

这个时候就行程了一个强持有问题
runloop -> timer -> self
那是不是跟block一样weakself就可以解决呢,这个时候模型就变成了
runloop -> timer -> weakSelf -> self
经过测试还是不行的没有打破这层强持有关系.那为什么呢
weakself加入到了弱引用表中,但是weakself和self一样么,先验证下

2020-05-13 15:45:24.514059+0800 强引用[66904:226978] 9
(lldb) p &self
(TimerViewController **) $0 = 0x0000000116b33fc8
(lldb) p &weakSelf
(TimerViewController *const *) $1 = 0x00007ffee1ff2c08
(lldb) 

发现他们是不相同的,只是指向了同一片地址.并且引用计数没有变化.并没有打破强持有关系,那么block为什么就可以,来我们看下block源码

void _Block_object_assign(void *destArg, const void *object, const int flags) {
    const void **dest = (const void **)destArg;
    switch (os_assumes(flags & BLOCK_ALL_COPY_DISPOSE_FLAGS)) {
      case BLOCK_FIELD_IS_OBJECT:
        /*******
        id object = ...;
        [^{ object; } copy];
        ********/

        _Block_retain_object(object);
      //objc 指针地址 weakself (self)
        *dest = object;
        break;
       default:
        break;
    }
}

const void **dest = (const void **)destArg;block操作的是指针地址,并没有直接持有self,只是持有了一个临时变量的指针地址
self -> block ->weakself (临时变量的指针地址) 所以打破了这层持有关系
而timer是直接操作的对象所以无法打破这层强引用关系

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容