rintaro
rintaro

Reputation: 51911

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?

Upvotes: 4

Views: 5192

Answers (2)

rintaro
rintaro

Reputation: 51911

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    if self.view.window == nil {
        self.setValue(nil, forKey: "view")
    }
}

Upvotes: 6

DarkDust
DarkDust

Reputation: 92306

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.

Upvotes: 3

Related Questions