Home > Software engineering >  'self' refers to the method 'EquationController.self', which may be unexpected
'self' refers to the method 'EquationController.self', which may be unexpected

Time:04-29

i tried to use lazy var but it didn't work, so i need to solve this cz the "Add Graph" button is not working:

var addGraphButton: NSButton = {
    let button = NSButton(title: "Add Graph", target: self, action: #selector (addGraph))
    button.translatesAutoresizingMaskIntoConstraints = false
    return button // 'self' refers to the method 'EquationController.self', which may be unexpected
}()

error

CodePudding user response:

In the context you posed, self refers to the EquationController type itself, not an object which is an instance of EquationController, which is what you intended.

I.e., self.performSelector(#selector(addGraph)) would end up calling class func addGraph, not your instance method func addGraph.

To fix this, make the variable lazy, which will defer the instantiation of the button to where you first use it, at which point the initialization of self is complete. You cannot reference self of the instance in a closure-initialized stored property unless you make it lazy. E.g.:

lazy var addGraphButton: NSButton = {
    let button = NSButton(title: "Add Graph", target: self, action: #selector(addGraph))
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

You said:

i tried to use lazy var but it didn’t work

This is the correct solution. You did not share your addGraph implementation, but make sure you add @objc qualifier. E.g., you would generally define the action to take one parameter:

@objc func addGraph(_ sender: Any) { ... }

And then:

lazy var addGraphButton: NSButton = {
    let button = NSButton(title: "Add Graph", target: self, action: #selector(addGraph(_:)))
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()
  • Related