Recently in an e-commerce project, because there are many interfaces have discounted items, discounted items will be time-limited, so there is a large number of timers to count the countdown. Each page is a timer. Feel too much performance, think of a more economical way of performance. Global on a timer, control all the countdown of the interface.
The project was swift3.0.
1, solve the idea:
Create a Timer class, this system is also a timer, the timer inside a proxy method, and then the timer execution method is the executor of the agent, the need to use the interface of the timer, to inherit the agent, and then implement the method of the agent line.
2. Code:
Timer class
Import UIKit
Protocol Ssttimerdelegate:class {
Func UpdateTime ()
}
Final class Ssttimer:nsobject {
Weak var delegate:ssttimerdelegate?
static Var Shared:ssttimer {
struct Static {
static Let Instance:ssttimer = Ssttimer ()
}
Return static.instance
}
Private override Init () {
Super.init ()
Timer.scheduledtimer (timeinterval:1.0, target:self, selector: #selector (didtimeralarm), Userinfo:nil, Repeats:true)
}
Func Didtimeralarm () {
Self.delegate?. UpdateTime ()
}
}
Other classes to use for timers:
1.
Class Viewcontroller:uiviewcontroller {
var i = 0
@IBOutlet weak var timelabel:uilabel!
Override Func Viewdidload () {
Super.viewdidload ()
}
Override Func Viewwillappear (_ Animated:bool) {
TimerUtil.shared.delegate = Self
}
}
Extension Viewcontroller:timerdelegate {
Func UpdateTime () {
i = i + 1;
Timelabel.text = "\ (i)"
}
}
2.
Class Viewthreevc:uiviewcontroller {
var i = 0
@IBOutlet weak var timelabel:uilabel!
Override Func Viewdidload () {
Super.viewdidload ()
}
Override Func Viewwillappear (_ Animated:bool) {
TimerUtil.shared.delegate = Self
}
}
Extension Viewthreevc:timerdelegate {
Func UpdateTime () {
i = i + 1;
Timelabel.text = "\ (i)"
}
}
This article is from the "Java" blog, so be sure to keep this source http://5378610.blog.51cto.com/5368610/1906259
IOS High Performance Timer solution