Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active December 9, 2019 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/09ce290c376e4937140367d63e7e632d to your computer and use it in GitHub Desktop.
Save robertmryan/09ce290c376e4937140367d63e7e632d to your computer and use it in GitHub Desktop.
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
}
}
}
@robertmryan
Copy link
Author

robertmryan commented Dec 9, 2019

This fixes a bunch of issues:

  1. You were creating a new DispatchWorkItem every time you click the button;
  2. You therefore were never canceling the dispatched work;
  3. The if (self?.work.isCancelled)! { ... } pattern is obviously a problem because if self is deallocated, your code would crash;
  4. You probably should set work to nil after you cancel it to release the memory associated with it.
  5. Also, the idea of 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 a sleep in there to avoid crushing the CPU on tons of unnecessary updates.
  6. There’s no benefit of using implicitly unwrapped optional. One small mistake and code could crash. Just make it an ordinary optional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment