views:

423

answers:

2

I am making my way thru the Hilgrass and Kochan books. Doing my own experiments to further my learning I simply want to create a cocoa interface with 4 textfields, 3 that accept numbers and the 4th that displays the sum of the other 3. I can do this using a button to do the calculation however what I want to do is have it autoupdate any time one of the 3 inputs is changed.

I have looked for a lesson that covers this, both in books and online but cannot find one, so either it's really simple and I'm missing something or it's not so simple. It appears the conventional way of doing this is with NSNotifactions but it is maybe possible with bindings as well?

What is the standard way of doing this is cocoa and is there a tutorial that anyone knows of?

Cheers, Morgan

+2  A: 

Chapter 7: Key-Value Coding; Key-Value Observing of the Hilgrass' "Cocoa Programming for Mac OS X" or Apple documentation on Key-Value Coding can help you accomplish this task.

Here is my sample xcode project: http://dl.getdropbox.com/u/344540/stackoverflow/AutoAdd.zip . You can control how the updating happens by using the "Bindings" tab of the Inspector for the NSTextFields in Interface Builder. There are other gems in that tab too.

phi
Thanks for the code sample! Much appreciated. I'll study the KVC stuff. Cheers! Morgan
Morgan McDermott
A: 

NSControl (and hence NSTextField) has a notification NSControlTextDidChangeNotification which will be sent whenever the text changes.

So you can register for that notification on your three text fields and then update your calculation field.

I took this a little further, creating a subclass of NSTextField called ActionOnChangeTextField which automatically calls its action whenever the text changes. So you just set the class of the three text fields to ActionOnChangeTextField and connect the selector to your update calculation method.

@interface ActionOnChangeTextField : NSTextField {

}

@end

@implementation ActionOnChangeTextField

- (void) doTextChangedAction:(NSNotification*)notification;
{
    [[self target] performSelector:[self action]];
}

- (void) awakeFromNib;
{
    [[NSNotificationCenter defaultCenter] addObserver:self
               selector:@selector(doTextChangedAction:)
                name:NSControlTextDidChangeNotification
                 object:self];
}

- (void) dealloc;
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

@end
Peter N Lewis