在单独的类中实现UITextFieldDelegate [英] Implementing UITextFieldDelegate in a separate class
问题描述
我想在与 UIViewController
分开的类中实现 UITextFieldDelegate
,但是当我这样做时,我得到一个 EXC_BAD_ACCESS
运行时异常。
I want to implement UITextFieldDelegate
in a class separate from the UIViewController
but when I do I get a EXC_BAD_ACCESS
exception at runtime.
为什么这样做有效:
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;
}
}
推荐答案
注意声明委托
:
unowned(unsafe) var delegate: UITextFieldDelegate?
MyTextFieldDelegate()
已创建,已分配给委托
,然后在 createUI()
返回时解除分配。它被ARC取消分配,因为没有任何东西拥有它。您遇到的问题正是 unsafe
警告您。
MyTextFieldDelegate()
is created, assigned to delegate
, and then deallocated when createUI()
returns. It is deallocated by ARC because nothing owns it. The problem you are experiencing is exactly what unsafe
is warning you about.
您需要创建一个强引用您的 MyTextFieldDelegate
实例。您还需要保证在取消分配文本字段之后才释放委托。
You need to create a strong reference to your MyTextFieldDelegate
instance. You also need to guarantee that the delegate is not deallocated until after the text field is deallocated.
注意此行为与<$之间的区别C $ C>弱。如果代表是
弱
而不是无主(不安全)
,那么它将变为nil
并且永远不会被调用,而不是在被调用时崩溃。
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.
这篇关于在单独的类中实现UITextFieldDelegate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!