简体   繁体   中英

Why is the 'view' property of UIViewController not optional in Swift?

I noticed that the view property of UIViewController isn't of type UIView? but UIView instead (ie not optional). Why is that? Aren't UIViewController's views supposed to be nil when not loaded yet?

The offical documentation states the following:

The view stored in this property represents the root view for the view controller's view hierarchy. The default value of this property is nil. .... The UIViewController class can automatically set this property to nil during low-memory conditions and also when the view controller itself is finally released.

From my understanding of Swift optionals, it seems that view should be declared as var view: UIView? since it may be nil at some point. Apple seems to state the opposite, can you explain my why?

What do you think?

It looks like view is a lazy property (but not using the lazy modifier) - in fact if you read the inline comment (cmd+click on the view property to open the source) it says:

The getter first invokes [self loadView] if the view hasn't been set yet. Subclasses must call super if they override the setter or getter.

and about loadView() :

This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.

I presume that:

  • the standard implementation creates an empty view if it is not instantiated otherwise
  • it is backed by an optional variable (not publicly accessible)
  • in case of low memory conditions, the backing variable is set to nil, releasing the view instance
  • if you try to access the property when the backing variable is nil, it creates a new instance

so its implementation should be conceptually similar to:

private var _view: UIView?

var view: UIView {
    if _view == nil {
        loadView()
    }
    return _view!
}

func loadView() {
    if _view == nil {
        // _view = something()
    }
}

The property is technically not nil. It initialises the view when the property is accessed first time. It is called lazy loading . That means, when you access the property you are guaranteed to receive a value. I think the documentation for this property is misleading if not even incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM