My colleagues and I prefer different approaches to solving one small task. We would like to know opinion of the community.
We have to process UITextField's text during editing. ( Text should be displayed in the view's title )
Two simplest approaches are:
1.Register for notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textFieldDidChangeNotification:)
name:UITextFieldTextDidChangeNotification
object:_titleTextField];
2.Use UITextFieldDelegate method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSMutableString *mutableString = [textField.text mutableCopy];
[mutableString replaceCharactersInRange:range withString:string];
// use mutableString for father processing
return YES;
}
Which approach is better and why? Is there any reason why some approach should be avoided in this situation?
UPDATE: ( Some clarifications )
We do not need any additional flexibility that is provided by delegate ( like possibility to disallow some editing) or notifications ( possibility to add several observers ). Our main question is "Is it a good practice to use NSNotifications if we can easily solve an issue with delegate?"
UPDATE2:
Thanks everyone who answered the question!
It seems that community's answer for question "is it a good practice to use NSNotifications if we can easily solve an issue with delegate?" is yes. But for our original issue we have found another (third) variant which is better than delegates and NSNotification (see accepted answer).
Since UITextField inherits from UIControl we also can use addTarget: action: forControlEvents:
[_textField addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];