无法在不写入 init 方法的情况下调用不同 class 中的方法

Not able to call method in diffrent class without write init method

我无法从另一个 class 调用 handleRegister 方法。

我创建了一个名为 A 的 class,它有 handleRegister 方法:

class A {
   static var a:A?
   init(){
      A.a = self
   }

   @objc func handleRegister(){
      print("Hello method1")
   }
}

ViewController class 从我调用 handleRegister 方法的地方:

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.
    }
}

在我的 ViewController class 中我有 btnFirst 现在我正在尝试为 btnFirst 添加目标并尝试调用 handleRegister 形式的方法class A 工作正常。

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

您正在 viewDidLoad 中创建 A class 对象,它将在 viewDidLoad 之后立即释放。在 A class 初始化程序中,您通过编写此 A.a = self 创建 A 的强引用(这就是调用按钮操作的原因)。只需在 viewDidLoad 之外创建 A class 对象,它就可以正常工作。