1. 程式人生 > >iOS 高效能定時器解決方案2(商品打折倒計時)

iOS 高效能定時器解決方案2(商品打折倒計時)

1、上一篇 iOS 高效能定時器解決方案有缺陷,上一篇用的是代理設計模式,當離開當前介面時,代理就失效了,所以定時器的代理事件就不再執行,導致出錯。現在這篇進行了改進,用通知實現。

2、還是會有一個全域性定時器

import UIKit
let NotifyUpdateTime = NSNotification.Name(rawValue:"notifyUpdateTime")
final class TimerUtil:NSObject {
    static var shared:TimerUtil {
        struct Static {
            static let instance: TimerUtil =TimerUtil()
        }
        return Static.instance
    }

    private overrideinit() {
        super.init()
        let timer = Timer(timeInterval: 1.0, target:self, selector: #selector(didTimerAlarm), userInfo:nil, repeats: true)
        RunLoop.main.add(timer, forMode:RunLoopMode.commonModes)
    }

    func didTimerAlarm() {
        NotificationCenter.default.post(name:NotifyUpdateTime, object:nil, userInfo:nil)
    }
}

controller 1

class ViewController:UIViewController {
     var i =0
    @IBOutletweak var label:UILabel!

    overridefunc viewDidLoad() {
        super.viewDidLoad()
    }

    overridefunc didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    overridefunc viewWillAppear(_ animated:Bool) {
        //接受time通知
        NotificationCenter.default.addObserver(self, selector:#selector(updateTime),

                                               name:NotifyUpdateTime, object: nil)
    }

    func updateTime() {
        i =i + 1;
        label.text ="\(i)"
    }
}

ccontroller 2

class ViewTwoVC:UIViewController {
    var i =0
    @IBOutletweak var timeLabel:UILabel!
    overridefunc viewDidLoad() {
        super.viewDidLoad()
    }

    overridefunc viewWillAppear(_ animated:Bool) {

        //接受time通知
        NotificationCenter.default.addObserver(self, selector:#selector(updateTime),

                                               name:NotifyUpdateTime, object: nil)

    }
    func updateTime() {
        i =i + 1;
        timeLabel.text ="\(i)"
    }
}