在单独的 class 中实现 UITextFieldDelegate
Implementing UITextFieldDelegate in a separate class
我想在与 UIViewController
分开的 class 中实现 UITextFieldDelegate
,但是当我这样做时,我在运行时遇到 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()
returns 时释放。它被 ARC 释放,因为没有人拥有它。您遇到的问题正是 unsafe
警告您的问题。
您需要创建对 MyTextFieldDelegate
实例的强引用。您还需要保证在解除分配文本字段之前不会解除分配委托。
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.
我想在与 UIViewController
分开的 class 中实现 UITextFieldDelegate
,但是当我这样做时,我在运行时遇到 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()
returns 时释放。它被 ARC 释放,因为没有人拥有它。您遇到的问题正是 unsafe
警告您的问题。
您需要创建对 MyTextFieldDelegate
实例的强引用。您还需要保证在解除分配文本字段之前不会解除分配委托。
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.