I am programmatically creating a button and am receiving this warning for every button I create when I add the "button.addTarget" line of code to it. The code is below:
let logoutButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Log Out", for: .normal)
button.setWidth(width: 100)
button.setHeight(height: 30)
button.layer.cornerRadius = 15
button.backgroundColor = .white
button.setTitleColor(.red, for: .normal)
button.addTarget(self, action: #selector(handleLogOut), for: .touchUpInside)
return button
}()
The warning I am getting for this is:
‘self’ refers to the method ‘HomeController.self’, which may be unexpected
And it also comes with a fix, which is:
Use ‘HomeController’ to silence this warning
However, when I implement this fix, the "self" in the first parameter of the "button.addTarget" line becomes "HomeController.self" and makes the app crash.
I always used to use "self" for this and it never gave warnings until recently. Now it gives a warning for this every time. When I use "self," it all still works fine, but the warnings in Xcode are annoying… any help is appreciated.
2
Answers
Use lazy var instead of let it will solve problem or set target in viewDidLoad.
You are creating a variable and assigning the result of a closure to that variable. That closure’s code executes before any instances of your class exist (Before there is a
self
to refer to.)Self does not exist at the time that code runs.
As Abhishek suggests in their answer (voted) if you switch your declaration to a lazy var, lazy vars get created the first time they are referenced.
self
exists when a lazy var’s value is computed.