Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a variable when IBOutlet is initialized?

It happened for me to write following code snippet in one of my UIViewControllers in my new iOS Swift Application.

var starButtonsCount = starButtons.count
@IBOutlet var starButtons: [UIButton]!

Then straight next to the starButtonsCount variable declaration following error appeared in red.

Error: Cannot use instance member ‘starButtons’ within property initializer; property initializers run before ‘self’ is available.

So I found out that by declaring the starButtonCount variable as lazy we can resolve this error (temporary in the long run of the iOS App development process).

I'm curious to find out what are the other methods to solve this?

Is there a way to trigger the initialization for starButtonCount when the starButtons IBOutlets get initialized?

like image 705
Randika Vishman Avatar asked Dec 16 '18 15:12

Randika Vishman


1 Answers

awakeFromNib is a method called when every object in a .xib have been deserialized and the graph of all outlets connected. Documentation says:

Declaration

func awakeFromNib()

Discussion

message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.The nib-loading infrastructure sends an awakeFromNib

You must call the super implementation of awakeFromNib to give parent classes the opportunity to perform any additional initialization they require. Although the default implementation of this method does nothing, many UIKit classes provide non-empty implementations. You may call the super implementation at any point during your own awakeFromNib method.

As in:

class MyUIViewController : UIViewController {
    var starButtonsCount = 0
    @IBOutlet var starButtons: [UIButton]!
    override func awakeFromNib() {
        super.awakeFromNib()
        starButtonsCount = startButtons.count
    }
}
like image 51
Jean-Baptiste Yunès Avatar answered Sep 26 '22 17:09

Jean-Baptiste Yunès