Skip to content

Instantly share code, notes, and snippets.

@almaleh
Last active June 3, 2021 10:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save almaleh/7e918ee284e67b2a8297b558f22a68ba to your computer and use it in GitHub Desktop.
Save almaleh/7e918ee284e67b2a8297b558f22a68ba to your computer and use it in GitHub Desktop.
// Can you tell which version has a retain cycle?
// Version A
class ViewControllerA: UIViewController {
var workItem: DispatchWorkItem?
override func viewDidLoad() {
let workItem = DispatchWorkItem {
UIView.animate(withDuration: 1.0) {
self.view.backgroundColor = .red
}
}
self.workItem = workItem
}
}
// Version B
class ViewControllerB: UIViewController {
var workItem: DispatchWorkItem?
override func viewDidLoad() {
let view = self.view
let workItem = DispatchWorkItem {
UIView.animate(withDuration: 1.0) { [weak self] in
view?.backgroundColor = .red
}
}
self.workItem = workItem
}
}
// Version C
class ViewControllerC: UIViewController {
var workItem: DispatchWorkItem?
override func viewDidLoad() {
let workItem = DispatchWorkItem {
UIView.animate(withDuration: 1.0) { [weak self] in
self?.view.backgroundColor = .red
}
}
self.workItem = workItem
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment