gpt4 book ai didi

ios - 在单独的类中实现 UITextFieldDelegate

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:19 26 4
gpt4 key购买 nike

我想实现 UITextFieldDelegate在与 UIViewController 分开的一个类中但是当我这样做时,我得到一个 EXC_BAD_ACCESS运行时异常。

那么为什么这样做:

class MyViewController : UIViewController, UITextFieldDelegate
{
...

func createUI()
{
let someTextField: UITextField = UITextField()
someTextField.delegate = self

...
}

func textFieldShouldReturn(textField: UITextField!) -> Bool
{
textField.resignFirstResponder()
return true;
}
}

但这不是:

class MyViewController : UIViewController
{
...

func createUI()
{
let someTextField: UITextField = UITextField()
someTextField.delegate = MyTextFieldDelegate()

...
}
}

class MyTextFieldDelegate : NSObject, UITextFieldDelegate
{
func textFieldShouldReturn(textField: UITextField!) -> Bool
{
textField.resignFirstResponder()
return true;
}
}

最佳答案

注意delegate的声明:

unowned(unsafe) var delegate: UITextFieldDelegate?

MyTextFieldDelegate() 被创建,分配给 delegate,然后在 createUI() 返回时释放。它被 ARC 释放,因为没有人拥有它。您遇到的问题正是 unsafe 警告您的问题。

您需要创建对 MyTextFieldDelegate 实例的强引用。您还需要保证在解除分配文本字段之前不会解除分配委托(delegate)。

Note the difference between this behavior and weak. If the delegate were weak instead of unowned(unsafe), then it would become nil and never get called, instead of crashing when it's called.

关于ios - 在单独的类中实现 UITextFieldDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28032973/

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