Journal

Cocoa: NSTextField and Receiving Events

Posted on February 27th, 2005 at 03:33 pm under Development

Q. How can I, using an NSTextField, determine when text has been entered or changed and then react to it?

It sounds like you’re asking how you can, say, toggle a checkbox (NSButton) to the on-state when text has been entered into a text field (NSTextField), akin to the way iTunes sets the checkbox when you modify a tag when editing multiple songs. This is actually quite a simple process and involves using the NSNotificationCenter to tell the system that you would like to be tracking such notifications.

To begin with, you’ll first need to tell the default NSNotificationCenter that you would like to begin receiving notifications each time the text has been changed in a text field. According to Apple’s documentation on the NSTextField, you can request to receive any of the following notifications:

NSControlTextDidBeginEditingNotification
NSControlTextDidChangeNotification
NSControlTextDidEndEditingNotification

In this case, we’re going to use NSControlTextDidChangeNotification as it will take care of letting us know if any text was entered. With this piece of knowledge, all we need to do is add the following code to the awakeFromNib method to tell the system we would like to begin receiving notifications:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:NSControlTextDidChangeNotification object:nil];

What this code does is tell the system that whenever any NSTextField’s have their contents changed, to send an NSNotification to a method called textDidChange: that we will write later. The observer is the control that will receive the notifcations, in this case it is our controller.

Next, we need to write our textDidChange: method and to do so, we will simply add a new method to our source with the following prototype:

- (void)textDidChange:(NSNotification *)aNotification

Now, whenever any NSTextField’s are modified in our program, this method will be run. By querying the NSNotification, we can determine which control was editied. In the following code, I’m checking to see if the control that sent the notification is called ‘artist,’ and if so, I’m simply setting my checkbox named ‘modifiedArtist’ to checked:

if ([aNotification object] == artist) {
[modifyArtist setState:NSOnState];
}

The last step in this process is to just make sure that you’ve set your connection for delegate in Interface Builder (from your Window to your Controller).

One Comment

I believe setting the the control delegate to be the controller and then implementing the:

- (void)controlTextDidChange:(NSNotification *)aNotification

Notification will do the same thing. Note that the notification is different between NSTextField and NSTextView which is how I found ths page.

Your idea works too.

Leave a Comment

Your Name ››
E-mail Address ››
Website ››
Comment ››