Ravi
Ravi

Reputation: 93

How IBoutlet hold initial value being weak? Means some other strong object is pointing?

I have created a button on storyboard and IBOutlet in source code for same.

When I try to re-initialize same outlet, its giving warning "Instance will be immediately deallocated because property 'button' is 'weak'".

I understand this point, because no strong pointer is pointing,so it will deallocate. But initially button has value, if it weak then there must be other object pointing it strongly?

Similar case for Layout constraints IBOutlet.

In the case of button , I think it must view(But not sure).

But what will it be in case of layout contraint.

What if I want to achieve same thing by creating UI programmatically.

I mean a weak variable can keep same values as holding in case of UI creation by IB.

Thanks in advance!

Upvotes: 0

Views: 126

Answers (1)

Paulw11
Paulw11

Reputation: 114773

When the scene is loaded from the storyboard the button is added to the view hierarchy before the reference is assigned to the @IBOutlet property. Since the button is in the view hierarchy there is a strong reference to it.

When you say something like

self.buttonOutlet = UIButton() 

The only reference to the new button is a weak property and the compiler warns you that the object will be immediately released.

You can use a local variable to hold a strong reference until the button is added to the view hierarchy.

let newButton = UIButton()
self.view.addSubview(newButton)
self.buttonOutlet = newButton

Upvotes: 3

Related Questions