views:

463

answers:

1

Hello fellow coders,

I have created a class, that makes it easy to enter in the amount for a particular price in the same way an ATM machine allows you to enter in an amount, user does not enter the decimal.

This is a generic class called (AmountPicker), so that it can be used among many other classes. I am using it by invoking the presentModalViewController method, this class uses a nib file. Inside the xib there is a hidden text field and a label along with a done button in the navigation bar. The done button is an IBAction connected to a method named doneButtonPressed.

I am wanting to know if it is possible to delegate this method to another class, so that the logic inside the method can differ from the one already defined inside the amountPicker class.

The reason is, I use the amountPicker Class in two places one for entering a purchase, which takes the label text and assigns the value to a variable inside the appDelegate, this was ok when i just used it in one class, but now there is a detailTableViewController of the purchase and this view will also need to provide a way to change the data in case it was entered wrong.

So in the detail view i am using a custom header, the custom header has a textField for the name of the purchase, a button to activate the AmountPicker, and a label for the amount, when the amount button is pressed then the AmountPicker class pops up and the user enters the amount and presses the done button, NOW, this is where i need to change the logic for the doneButton, instead of using a variable in the appDelegate.

I was thinking that the DetailTableViewController could act as a delegate for the amountPicker Class and override the doneButtonPressed method, so that the amountLabel can be updated with the new amount.

Is this possible, if not what is the right way?

+2  A: 

Your thinking is right along with how delegation is normally used. What I would do is create an Objective-C protocol, maybe AmountPickerDelegate. Then, in your interface for the AmountPicker, you would have this:

@interface AmountPicker : NSObject {
    NSString *someValue;
    ...
    id <AmountPickerDelegate> delegate;
}

@property (assign) id <AmountPickerDelegate> delegate;

@end

Then, in your delegate class, you would do this:

@interface DetailTableViewController : UITableViewController <AmountPickerDelegate>

Finally, in the original AmountPicker class, you could call something like this:

[delegate amountPickerDidPressDoneButton];

which would execute in the delegate.

Jeff Kelley