iOS开发知识小集

一个可以自动释放的定时器(Timer)

2018-08-12  本文已影响122人  Aiewing

现在开始

1.自动释放的假想

2.中介Target

typealias TimerBlock = () -> Swift.Void

class TimerTarget: NSObject {
    
    weak var target: AnyObject?
    var timer: Timer?
    var name: String?
    var block: TimerBlock?
    
    /// 初始化
    init(target aTarget: AnyObject?, name aName: String?, block aBlock: TimerBlock?)
    {
        target = aTarget as AnyObject
        name = aName
        block = aBlock
    }
    
    convenience override init() {
        self.init(target: nil, name: nil, block: nil)
    }
    
    @objc func aiewing()
    {
        guard let _ = self.target,
        let block = self.block else {
            self.timer?.invalidate()
            self.timer = nil
            guard let name = self.name else {
                return
            }
            print("Timer called \(name) has been invalidated")
            return
        }
        
        // 执行block
        block()
    }
}

3.Timer类扩展

extension Timer
{
    class func scheduledTimerAutoToRelease(timeInterval ti: TimeInterval, target aTarget: AnyObject, name aName: String, userInfo aUserInfo: Any?, repeats yesOrNo: Bool, block aBlock: @escaping TimerBlock) -> Timer
    {
        let timerTarget: TimerTarget = TimerTarget(target: aTarget, name: aName, block: aBlock)
        let timer: Timer = Timer.scheduledTimer(timeInterval: ti, target: timerTarget, selector: #selector(timerTarget.aiewing), userInfo: aUserInfo, repeats: yesOrNo)
        timerTarget.timer = timer
        return timer
    }
}

结束

上一篇下一篇

猜你喜欢

热点阅读