Reputation: 22683
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
Upvotes: 3
Views: 1156
Reputation:
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!
Upvotes: 0
Reputation: 4259
unowned var foo: UITextField
should be initialized during view controller initialization, but it's impossible because outlet can be initialized only after view is created, and view is created only when view controller is shown (more precisely when view
property is accessed).
Upvotes: 0
Reputation: 1380
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!
Upvotes: 0
Reputation: 131418
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.)
Upvotes: 0
Reputation: 535149
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.
Upvotes: 6