简体   繁体   中英

Why doesn't Xcode make outlets unowned instead of weak?

Xcode produces outlets as weak vars with implicit unwrapping, like this:

@IBOutlet weak var nameTextField: UITextField!

I wonder why it didn't just make onowned var , which - in my understanding - behaves exactly the same, but keeps the type non-optional. Is there any difference between these two?

weak var foo: UITextField!
unowned var foo: UITextField

A weak variable has a default value, namely nil , so your code is legal because the outlet property has a value at object creation time ( before the outlet is actually connected).

But an unowned variable would have no default value and your code wouldn't compile. Try it.

Also the entire concept would be wrong. unowned is for a thing with a guaranteed independent existence and which you can't live without. A subview of a view controller's view satisfies neither of those.

Yes, there is difference. Other than the default value issue, there is a way to check whether or not the weak value currently exists:

if let nameTextField = nameTextField {
    // do smth
}

on the other hand, I don't think there is a way to check if the unowned is there and valid to access. Whenever an unowned is used, it's supposed to always be there, which is not true in the case of IBOutlet . The outlets are not set until the view controller is loaded from the storyboard.

Hope this helps!

Unowned types are dangerous and best avoided. An unowned variable is equivalent to the Objective C unsafe_unretained type.

If the object that's pointed to by an unowned reference gets released, the unowned reference won't be set to nil. If you then try to reference the object later, your code can't tell if it's still valid or not. If you try to call a method or read/write an instance variable, you may crash if the object has been released.

(Then there's the fact that the variable doesn't have a default value, as matt says in his answer.)

unowned var foo: UITextField应该在视图控制器初始化期间初始化,但这是不可能的,因为只有在创建视图之后才能初始化 outlet,并且只有在显示视图控制器时才创建视图(更准确地说是在访问view属性时)。

It used to be that optionals could not be unowned . That's possible now, so unowned is appropriate. This is probably not done automatically because it would confuse somebody.

@IBOutlet private unowned var uiObject: UIObject!

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