ios - 不写 init 方法就无法调用不同类中的方法

标签 ios objective-c iphone swift init

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

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

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

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

ViewController 我调用 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 类中,我有 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 类对象,它将在 viewDidLoad 之后立即释放。在 A 类初始值设定项中,您通过编写此 A.a = self 创建了 A 的强引用(这就是调用按钮操作的原因)。只需在 viewDidLoad 之外创建 A 类对象,它就可以正常工作。

关于ios - 不写 init 方法就无法调用不同类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41033929/

相关文章:

objective-c - 方法实现末尾的分号

ios - AVCaptureOutput didOutputSampleBuffer 停止被调用

iphone - 如何创建一个同步的NSURLConnection请求

iphone - 有没有其他方法可以在不越狱的情况下查看 iOS 应用程序的大小?

ios - 导航项标题问题

objective-c - 访问已发布的 NSString 不会使应用程序崩溃

ios - 如何在 IOS 中实现纯搜索栏

iphone - iphone 字体粗体问题

ios - 协议(protocol)方法如何在类中设置变量?

iphone - CTServerConnectionGetCellID 例程核心电话