Reputation: 149
If i create an new "Single View Application" project with xcode(6.3.2) and add only a deinit function to the ViewController. Run app, close app. Deinit is never called! I tested it with several devices and the simulator.
deinit {
println("deinit:")
}
Why is that? Is that the standard behaviour? What can i do to make it work?
/* Edit */ After reading the comments i put this code to my Viewcontroller.
import UIKit
class A {
func test() {
println("A test")
}
deinit {
println("A deinit")
}
}
class ViewController: UIViewController {
var a:A? = A()
override func viewDidLoad() {
super.viewDidLoad()
println("ViewController viewDidLoad")
a?.test()
}
override func viewDidDisappear(animated:Bool) {
println("ViewController viewDidDisappear")
a = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
println("ViewController didReceiveMemoryWarning")
}
deinit {
println("ViewController deinit")
a = nil
}
}
Now i get
ViewController viewDidLoad:
A test
ViewController viewDidDisappear:
A deinit
Does this mean that i have to cleanup my objects by hand within the viewDidDisappear call because the view controllers deinit function is not reliable?
Upvotes: 3
Views: 1118
Reputation: 11646
As apple states in documentation, App termination is done via SIGKILL that it a lot faster than exiting via sending message.
So no code will be called, neither applicationWillTerminate, for example.
try this code:
// CustomView.swift
import UIKit
class CustomView: UIView {
deinit{
print("Swift CustomView dying...\n")
}
}
in controller:
var v : CustomView?
v = CustomView(frame: CGRectZero)
v = nil
You will we in console:
Swift CustomView dying...
A Sample project is available on request. (write me)
Upvotes: 1
Reputation: 7549
No. In this case the ViewController deinit isn't even being called because ViewController doesn't go out of memory.
A way to test this is to create a new ViewController and replace the current ViewController with it. This should remove your current ViewController out of the memory, hence calling it's deinit method.
Upvotes: 1