Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unload self.view from UIViewController in Swift

According to View Controller Programming Guide, we can explicitly unload self.view from UIViewController by assigning nil to self.view.

But in Swift, view property in UIViewController is declared as

var view: UIView

It's not UIView! and thus following code not compiles

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    if self.view.window == nil {
        self.view = nil
        //          ^ Type 'UIView' does not conform to protocol 'NilLiteralConvertible'

    }
}

Is there another way to do it in Swift?

like image 508
rintaro Avatar asked Oct 20 '25 19:10

rintaro


2 Answers

setValue(nil, forKey:"view") seems to work:

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    if self.view.window == nil {
        self.setValue(nil, forKey: "view")
    }
}
like image 100
rintaro Avatar answered Oct 22 '25 09:10

rintaro


You are no longer expected to unload the view. This is why -[UIViewController viewDidUnload] is deprecated. The documentation says:

Deprecated in iOS 6.0. Views are no longer purged under low-memory conditions and so this method is never called.

In the View Controller Programming Guide, it says:

The memory used by a view to draw itself onscreen is potentially quite large. However, the system automatically releases these expensive resources when the view is not attached to a window. The remaining memory used by most views is small enough that it is not worth it for the system to automatically purge and recreate the view hierarchy.

In other words: if the view hierarchy is attached to a window, it can consume a lot of memory. But if the view hierarchy is not attached to a window it's pretty cheap.

So the answer is: don't try to unload your view. It wouldn't give you much memory back anyway. Of course, if you can release any objects that you can restore/recalculate (like caches), do so in didReceiveMemoryWarning.

like image 43
DarkDust Avatar answered Oct 22 '25 10:10

DarkDust



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!