123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- //
- // PQWeakTimer.swift
- // PQSpeed
- //
- // Created by lieyunye on 2020/6/18.
- // Copyright © 2020 BytesFlow. All rights reserved.
- //
- import Foundation
- public class PQWeakTimer {
- public weak var timer: Timer?
- public weak var target: AnyObject?
- public let action: (Timer) -> Void
- public init(timeInterval: TimeInterval,
- target: AnyObject,
- repeats: Bool,
- action: @escaping (Timer) -> Void)
- {
- self.target = target
- self.action = action
- timer = Timer.scheduledTimer(timeInterval: timeInterval,
- target: self,
- selector: #selector(fire),
- userInfo: nil,
- repeats: repeats)
- }
- public class func scheduledTimer(timeInterval: TimeInterval,
- target: AnyObject,
- repeats: Bool,
- action: @escaping (Timer) -> Void) -> Timer
- {
- return PQWeakTimer(timeInterval: timeInterval,
- target: target,
- repeats: repeats,
- action: action).timer!
- }
- @objc public func fire(timer: Timer) {
- if target != nil {
- action(timer)
- } else {
- timer.invalidate()
- }
- }
- }
|