Last active
December 9, 2019 20:41
-
-
Save robertmryan/09ce290c376e4937140367d63e7e632d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
@IBOutlet weak var label: UILabel! | |
@IBOutlet weak var button: UIButton! | |
var isStart = false | |
var work: DispatchWorkItem? | |
private func getCurrentTime() -> DispatchWorkItem { | |
return DispatchWorkItem { [weak self] in | |
while self?.work?.isCancelled == false { | |
let date = Date() | |
let component = Calendar.current.dateComponents([.second], from: date) | |
DispatchQueue.main.async { | |
self?.label.text = "\(component.second!)" | |
} | |
Thread.sleep(forTimeInterval: 1) | |
} | |
} | |
} | |
@IBAction func btnPressed(_ sender: Any) { | |
isStart = !isStart | |
button.setTitle(isStart ? "Stop" : "Start", for: .normal) | |
let globalQueue = DispatchQueue.global(qos: .background) | |
if isStart { | |
let item = getCurrentTime() | |
globalQueue.async(execute: item) | |
work = item | |
} else { | |
work?.cancel() | |
work = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This fixes a bunch of issues:
DispatchWorkItem
every time you click the button;work
;if (self?.work.isCancelled)! { ... }
pattern is obviously a problem because ifself
is deallocated, your code would crash;work
tonil
after you cancel it to release the memory associated with it.while true { ... }
loop is a really bad idea, but I’m assuming you did that just for illustrative purposes. But, I’d at least insert asleep
in there to avoid crushing the CPU on tons of unnecessary updates.