我想实现 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 wereweak
instead ofunowned(unsafe)
, then it would becomenil
and never get called, instead of crashing when it's called.
关于ios - 在单独的类中实现 UITextFieldDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28032973/