Using the following method does not hold the object.
method 1:
import UIKit
class SomeViewController: UIViewController {
let value = "something"
deinit {
print("Test: deinit")
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
dismiss(animated: true) {
print("Test: dismiss ended")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
guard let sself = self else { return }
print("Test: then delayed 2s, \(sself.value)")
}
}
}
}
class MainViewController: UIViewController {
@objc func onAction(_ sender: Any) {
present(SomeViewController(), animated: true, completion: nil)
}
}
print:
Test: dismiss ended
Test: deinit
method 2:
import UIKit
class SomeViewController: UIViewController {
let value = "something"
deinit {
print("Test: deinit")
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
dismiss(animated: true) {
print("Test: dismiss ended")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
withExtendedLifetime(self) {
print("Test: then delayed 2s, \(self?.value ?? "nothing")")
}
}
}
}
}
class MainViewController: UIViewController {
@objc func onAction(_ sender: Any) {
present(SomeViewController(), animated: true, completion: nil)
}
}
print:
Test: dismiss ended
Test: deinit
Can only make it work by removing weak
keyword.
import UIKit
class SomeViewController: UIViewController {
let value = "something"
deinit {
print("Test: deinit")
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
dismiss(animated: true) {
print("Test: dismiss ended")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
withExtendedLifetime(self) {
print("Test: then delayed 2s, \(self.value)")
}
}
}
}
}
class MainViewController: UIViewController {
@objc func onAction(_ sender: Any) {
present(SomeViewController(), animated: true, completion: nil)
}
}
print:
Test: dismiss ended
Test: then delayed 2s, something
Test: deinit