Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the initialization to `weak` return `nil` in Swift?

Why does the initialization to weak var return the variable as nil while the initialization to the usual var return the expected result? In the following code on ViewController.swift:

weak var myButton: UIButton!
var myButtonNotWeak: UIButton!

override func viewDidLoad() {
    let frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    myButton = UIButton(frame: frame)
    myButtonNotWeak = UIButton(frame: frame)
    print("\(myButton), \(myButtonNotWeak)")
}

This logs the following to the console:

nil, <UIButton: 0x7f946bc424a0; frame = (0 0; 100 100); opaque = NO; layer = <CALayer: 0x7f946bc42920>>

But why does the first return nil? I think if you define a variable as weak, then when the view controller that defined the "weaked variable" (self in this case) is gone, the "weaked variable" is gone in accordance with it. However, I believe I don't remove the instance of the ViewController in the code not assign nil to it, especially within its viewDidLoad() method.

So if I get it correctly, why does the "weaked variable" return nil when initiated? When I use it with @IBOutlet, then it doesn't become nil (but I don't need to explicitly inistantiate it, though). And should I define the instance variable without weak when I want to inistantiate it from within code, especially within viewDidLoad()?

I want to retain the variable outside of viewDidLoad() because I want to refer to the instance from other methods. What's the best way in this case?

like image 782
Blaszard Avatar asked Oct 01 '14 08:10

Blaszard


1 Answers

weak means that variable doesn't retain the object and it will be deallocated if there are no other strong references to it. @IBOutlet weak variables are not nil, because those views have strong references from view controllers view hierarchy.

You have to refer with strong reference to your button and add it to view hierarchy before you can assign it to weak property, or simply don't use weak property.

like image 172
Kirsteins Avatar answered Oct 04 '22 02:10

Kirsteins