Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textDidChange not called ( NSTextFieldDelegate )

Step 1. Add a NSTextField in xib

Step 2. Add NSTextFieldDelegate in .h file,Control-drag NSTextField to File's Owner to set delegate to it

Step 3, In .m file add the method:

- (void)textDidChange:(NSNotification *)notification{
    NSLog(@"textDidChange");
}

but the method textDidChange: not called?

Is any mistake?

like image 958
Mil0R3 Avatar asked Nov 30 '22 23:11

Mil0R3


2 Answers

The file's owner isn't the app delegate -- is the app delegate where you put that method? You should control drag to the blue cube labeled app delegate.

After Edit: The message that the delegate receives is controlTextDidChange: not textDidChange, so implement that one instead.

like image 75
rdelmar Avatar answered Dec 04 '22 05:12

rdelmar


You need to register an observer to listen for the NSNotification.

// When the NSWindow is displayed, register the observer.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(controlTextDidChange:) name:NSControlTextDidChangeNotification object:nil];

- (void)controlTextDidChange:(NSNotification *)obj {
    // You can get the NSTextField, which is calling the method, through the userInfo dictionary.
    NSTextField *textField = [[obj userInfo] valueForKey:@"NSFieldEditor"];
}

It seems, the object returned by NSFieldEditor is a NSTextView, instead of the same NSTextField object, which you may expect.

However, according to Apples documentation, if you implement this method and the controls delegate is registered to this object, the notification shall be automatically registered.

The control posts a NSControlTextDidChangeNotification notification, and if the control’s delegate implements this method, it is automatically registered to receive the notification

Source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSControl_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/controlTextDidChange:

like image 24
Leandros Avatar answered Dec 04 '22 06:12

Leandros