Reputation: 1946
I am not able to call handleRegister
method on tap from another class.
I created a class named A
which has handleRegister
method:
class A {
static var a:A?
init(){
A.a = self
}
@objc func handleRegister(){
print("Hello method1")
}
}
ViewController
class from where i am calling handleRegister
method:
class ViewController: UIViewController {
@IBOutlet weak private var btnFirst :UIButton?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let obj = A()
btnFirst?.addTarget(obj, action: #selector(obj.handleRegister), for: UIControlEvents.touchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In my ViewController
class i have btnFirst
now i am trying to add target for btnFirst
and try to calling handleRegister
method which is form class A
which is working fine.
But my question is when i comment init method in class A then i m not able to call method
handleRegister
.can anyone tell me why
init
method important to add button target of another class
Upvotes: 1
Views: 110
Reputation: 9226
You are creating A
class object in viewDidLoad
which will get deallocated immediately after the viewDidLoad. in A
class initializer you are creating strong reference of A by writing this A.a = self
(that's why your button action is called). Simply create A
class object outside viewDidLoad
and it will work fine.
Upvotes: 2