gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:50 24 4
gpt4 key购买 nike

我无法从另一个类调用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com