Reputation: 2291
I have a NSTextField
in my app, and I want to update the input when user gives me some bad input.
Also, I've bound the value of this text field control to a member variable. I've extracted a minimal project:
Here's the binding:
Eveything is simple, and finally in code I've set the initial value to Hello, World
, and I've also implemented controlTextDidChange:
method from NSControlTextEditingDelegate
.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
self.text = @"Hello, World";
}
- (void)controlTextDidChange:(NSNotification *)obj
{
NSLog(@"Changed Value: %@", [[obj object] stringValue]);
self.text = @"What??";
}
When I start typing in the text field, I did get change notification, except the value in the text field is not updated. I'm wondering why and how can I update text value in the text field with change of self.text
.
PS: I know I can do this by adding an outlet
of that text field, and manually set stringValue
, but I don't want to do that. Because it breaks the low coupling
rule, right?
Upvotes: 1
Views: 1802
Reputation: 24439
To make bindings validate values automatically there is mechanism of Key-Value Validation.
In the object you bind to (the App Delegate) implement either of the following methods:
- (BOOL) validateValue:(inout id *)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;
- (BOOL) validateText:(inout id *)ioValue error:(out NSError **)outError;
The first one is generic and will be called to all keys, the second one will be called specifically for key text
.
Enable “Validates Immediately” checkbox.
If validation method returns NO
, a standard error sheet will be displayed, with options to revert value back to what it was before editing, and to continue editing without setting value in the model object (the App Delegate).
Upvotes: 4