iOS中Timer循环引用的原因以及解决办法。

循环引用是iOS面试当中经常会被问到的东西,而在循环引用当中,最典型的是Timer造成的循环引用,Timer为什么会造成循环引用,这要从Timer的创建方式来看。

public /*not inherited*/ init(timeInterval ti: TimeInterval, invocation: NSInvocation, repeats yesOrNo: Bool)

public /*not inherited*/ init(timeInterval ti: TimeInterval, target aTarget: Any, selector aSelector: Selector, userInfo: Any?, repeats yesOrNo: Bool)

这两种方式创建出来的timer是不能直接使用的,需要添加到一个runloop中才能正常运作。注意,注释当中的 not inherited 表示这个方法不能被继承。

RunLoop.current.add(timer, forMode: .common)

还有另外两种创建方式

open class func scheduledTimer(timeInterval ti: TimeInterval, invocation: NSInvocation, repeats yesOrNo: Bool) -> Timer

open class func scheduledTimer(timeInterval ti: TimeInterval, target aTarget: Any, selector aSelector: Selector, userInfo: Any?, repeats yesOrNo: Bool) -> Timer

这两种方式创建出来的Timer会被自动加入到当前线程的runloop当中。
以上初始化方法当中有一个特别的参数
NSInvocation
这个东西留到下篇再说明。
按照正常的流程写出来的Timer应该是这样的:

let timer:Timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerDo), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .common)

@objc private func timerDo(){
        debugPrint("timer is runing \(Date.init())")
    }

然而却发现VCpop之后,定时器并没有停止输出,deinit方法也没有执行,这就是循环引用了。
为什么会循环引用呢,关键就是target,这个Timer的addTarget和UIButton的addTarget有什么不同,很明显,button对target是弱引用,Timer对target是强引用。

 // add target/action for particular event. you can call this multiple times and you can specify multiple target/actions for a particular event.
    // passing in nil as the target goes up the responder chain. The action may optionally include the sender and the event in that order
    // the action cannot be NULL. Note that the target is not retained.
    open func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event)

timer对当前对象是强引用,当前对象又持有这个timer。。。

最容易想到的解决办法:

1.在func viewDidAppear(_ animated: Bool)中手动释放

这样有个问题,万一当前页面没有被pop,而是push或者present了一个新的VC呢,这样不就破坏了正常的业务逻辑了?所以这种方式行不通。

2.使用weak关键字修饰

一说到循环引用很容易就想到weak,但是我要说的是,这里用weak不行。为什么用weak不行,这要从weak修饰的对象的释放时机说起,用了weak关键字修饰之后,系统会在一个hash表中增加一对key value,key就是这个对象的hash值,value就是这个对象的指针地址。
我们都知道每一个runloop都有自己的一个autorelease pool,在一次runloop结束之后会销毁这个autorelease pool,在释放这个autorelease pool的时候,也会到hash表中找到weak的对象把它和它的指针都释放掉,同时,那么问题来了,我这个timer是在runloop里面重复执行的,换而言之,这个runloop是一直在执行的,所以这个池子根本不会释放啊有木有。所以用它没什么卵用啊。

3.为什么不在deinit方法里面释放?

denint方法都不执行了,写了也没用。

4.不把timer作为当前对象的属性行不行。这样当前对象就不会持有timer了。

由于timer已经加入到runloop中,而且是个重复循环操作,所以这个runloop好像停不下来了。。。所以timer也就无法释放,而他对当前的对象又是强引用。

怎么解决

1.不让timer直接引用当前类

WX20181204-150627@2x.png

既然这样,那就给中间加一层想办法破坏这个循环引用。


WX20181204-151203@2x.png

创建一个中间类:

class TimerProxy{
    
    private weak var target:AnyObject?//一定要是弱引用
    
    private var selector:Selector?
    
    init(with target:AnyObject, selector:Selector) {
        self.target = target
        self.selector = selector
    }
    
    @objc public func executeSelector(){
        if (target != nil) && (selector != nil) {
            target?.perform(selector, with: nil)
        }
    }
    deinit {
        debugPrint("TimerProxy已释放")
    }
}

使用的时候 这样使用:

 let proxy = TimerProxy.init(with: self, selector: #selector(timerDo))
        timer = Timer.init(timeInterval: 1, target: proxy, selector: #selector(proxy.executeSelector), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .common)

deinit {
        debugPrint("TimerViewController已释放")
        timer?.invalidate()
        timer = nil
    }

等于是在proxy和viewController这里打破了强引用。
输出如下:

"timer is runing 2018-12-04 07:43:50 +0000"
"timer is runing 2018-12-04 07:43:51 +0000"
"TimerViewController已释放"
"TimerProxy已释放"

在TimerProxy的executeSelector方法中加判断的原因是,根据输出,TimerProxy的释放是晚于ViewController的,这样会造成VC被释放,但是timer还在执行,但是target和selector却没有了的情况。

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

相关阅读更多精彩内容

  • OC语言基础 1.类与对象 类方法 OC的类方法只有2种:静态方法和实例方法两种 在OC中,只要方法声明在@int...
    奇异果好补阅读 9,847评论 0 11
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,912评论 1 32
  • 如果宝宝现在想到了一个图案,磁性拼图七巧板都会马上呈现出来。宝宝只需要发挥想象力,用磁性拼图拼出来就可以啦! 灯笼...
    深优U妈咪阅读 3,800评论 0 0
  • 每当喝醉或者深更半夜睡不着,总是想给前任打个电话。白天醒来,又总会无比懊恼。当那个情绪来临,即使知道自己这样很傻,...
    丹阳君阅读 1,684评论 0 1
  • ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​
    七景鸣阅读 721评论 0 0

友情链接更多精彩内容