maseth maseth - 4 months ago 38
Objective-C Question

ControlTextDidChange not called on setStringValue

I've implemented a delegate and its

controlTextDidChange
method it is called whenever i enter text in the
NSTextField
.

When I set text programmatically via
[field setStringValue:@"newText"]
the
controlTextDidChange
is NOT called.

Could you please explain this? And how I should programmatically set a new value that triggers invocation of my delegate's method
controlTextDidChange
.

Answer

The controlTextDidChange delegate is only triggered on user interaction,
updating the NSControl manually does by design not trigger the delegate.

Proper Solution

The solution is to create a separate method to handle the text change:

- (void)myCustomFunction {
     // Triggered in case the text is changed,
     // no matter by user or programmatically
}

Trigger this method from the delegate:

- (void)controlTextDidChange:(NSNotification *)aNotification {
    [self myCustomFunction];
}

And in case the text is changed programmatically:

[theField setStringValue:@"text"];
[self myCustomFunction];

Now you can handle both situation within the same method.