Embedding UITextFieldDelegate in a Separate Class

I want to implement UITextFieldDelegate in a class other than UIViewController , but when I do this, I get an EXC_BAD_ACCESS exception at runtime.

So why does this work:

 class MyViewController : UIViewController, UITextFieldDelegate { ... func createUI() { let someTextField: UITextField = UITextField() someTextField.delegate = self ... } func textFieldShouldReturn(textField: UITextField!) -> Bool { textField.resignFirstResponder() return true; } } 

But this is not so:

 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; } } 
+6
source share
1 answer

Note the delegate declaration:

 unowned(unsafe) var delegate: UITextFieldDelegate? 

MyTextFieldDelegate() is created, delegate is assigned, and then freed when createUI() returns. He is freed by the ARC because nothing owns it. The problem you are facing is exactly what unsafe warns about.

You need to create a strong link to your instance of MyTextFieldDelegate . You must also ensure that the delegate is not freed until the text field is freed.

Note the difference between this behavior and weak . If the delegate was weak instead of unowned(unsafe) , then it will become nil and will never be called, and not fail when called.

+7
source

Source: https://habr.com/ru/post/981238/


All Articles