Home > DeveloperSection > Articles > iOS : Creating Sample on Delegate Method

iOS : Creating Sample on Delegate Method


iPhone iPhone  Ios  Objective C 
Ratings:
1 Comment(s)
 814  View(s)
Rate this:

 iOS : Creating Sample on Delegate Method


Let's assume an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action. This is achieved with the help of delegates.


The key concepts in the above example are −


  • A is a delegate object of B.
  • B will have a reference of A.
  • A will implement the delegate methods of B.
  • B will notify A through the delegate methods.

 

Steps in Creating a Delegate


Step 1. First, create a single view application and named it DelegateExample.

Step 2. Then select File -> New -> File...

Step 3. Then, in iOS Cocoa Touch section select objective-C class and click Next.

Step 4. Give a name to the Class “EnterAmountViewController” and select Subclass “NSObject”.

Step 5. and then select create.

Step 6. Add a protocol to the EnterAmountViewController.h file and the updated code is as follows −


#import< UIKit/UIKit.h>

//delegate to return amount entered by the user

/*This is the delegate declaration. For our delegate we only have one method which will be sending back to our root view controller an NSInteger which we will get from the user. */

@protocol EnterAmountDelegate <NSObject>

-(void)amountEntered:(NSInteger)amount; @end

 @interface EnterAmountViewController : UIViewController { id<EnterAmountDelegate> delegate;

}

@property(nonatomic,assign)id delegate;

@end

Step 7. Next open up EnterAmountViewController.m and specifically look at this function:

-(IBAction)savePressed

{

    //Is anyone listening

    if([delegate respondsToSelector:@selector(amountEntered:)])

    {

        //send the delegate function with the amount entered by the user

        [delegate amountEntered:[amountTextField.text intValue]];

    }

 

    [self dismissModalViewControllerAnimated:YES];

}

This function is connected to the save button on the toolbar which would be when the user is done entering their number(which doesn't really mean anything). This is the point where we're gonna call the delegate function which we declared in the .h. Before we call the function we first check if anyone is listening with if([delegate respondsToSelector:@selector(amountEntered:)]) If someone is listening then we call amountEntered with the integer value of our text field.

 

Step 8. Next open up DelegateExampleViewController.h

The one line to pay attention to is

@interface DelegateExampleViewController : UIViewController {

where the the view controller is being declared as an "EnterAmountDelegate" which is saying that it will implement all required delegate functions and may implement some or all of the optional delegate functions. In our example we only have one optional delegate function.

 

Step 9. Now, add two labels and one button in the DelegateExampleViewController.xib file, rename first label with text “Enter Amount”, and the second label rename it and set the text “0” (in this label we will change the numeric value with the help of delegate method) and change the text of UIButton with “Change Amount”. (see the sample below)


 

Step 10. Now add a new UIView in this application and named it “EnterAmountViewController” and after adding the view file, add a UIToolbar on the top in the EnterAmountViewController.xib by dragging the toolbar from the object library to UIView as shown below, like this add two UIBarButtonItem on the UIToolbar and fix one at the left side and set its identifier “cancel” and fix the second one at the right side and set its identifier “save” from the list. (see the sample below)


 

Step 11. Finally up DelegateExampleViewController.m

#pragma mark EnterNumbe Delegate function

//display the amount in the text field

-(void)amountEntered:(NSInteger)amount {

    amountLabel.text = [NSString stringWithFormat:@"%i" , amount];

}

This is delegate function being implemented in our view controller. This function will be called from EnterAmountViewController and we know it will contain our user input which we care about. All we are doing is taking that value and displaying it as a string in our UILabel. 

Step 12. Create an IBOutlet for the UITextField name it as “amountTextField” and UILabel name it as “amountLabel” in EnterAmountViewController.xib and DelegateExampleViewController.xib. That's it.

Here is the complete Source Code:

DelegateExampleAppDelegate.h file:

#import< UIKit/UIKit.h>

@class DelegateExampleViewController;

@interface DelegateExampleAppDelegate : NSObject <UIApplicationDelegate> {

UIWindow *window;

DelegateExampleViewController *viewController;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet DelegateExampleViewController *viewController;

@end

 

DelegateExampleAppDelegate.m file:

 

#import "DelegateExampleAppDelegate.h"

#import "DelegateExampleViewController.h"

@implementation DelegateExampleAppDelegate

@synthesize window;

@synthesize viewController;

#pragma mark -

#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch.

// Add the view controller's view to the window and display.

[self.window addSubview:viewController.view];

[self.window makeKeyAndVisible];

return YES;

}

.

.

- (void)dealloc {

[viewController release];

[window release];

[super dealloc];

}

@End

DelegateExampleViewController.h file:


#import< UIKit/UIKit.h>

#import "EnterAmountViewController.h"

@interface DelegateExampleViewController : UIViewController <EnterAmountDelegate>{ 

IBOutlet UILabel *amountLabel;

}

-(IBAction)changeAmountPressed;

@end

DelegateExampleViewController.m file:

#import "DelegateExampleViewController.h"

@implementation DelegateExampleViewController

-(IBAction)changeAmountPressed

{

EnterAmountViewController * enterAmountVC = [[EnterAmountViewController alloc]initWithNibName:@"EnterAmountViewController" bundle:nil];

//important to set the viewcontroller's delegate to be self

enterAmountVC.delegate = self;

[self presentModalViewController:enterAmountVC animated:YES];

}

#pragma mark EnterNumbe Delegate function

//display the amount in the text field

-(void)amountEntered:(NSInteger)amount

{

amountLabel.text = [NSString stringWithFormat:@"%i" , amount];

}

- (void)didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview.

[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.

}

- (void)viewDidUnload {

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (void)dealloc {

[super dealloc];

}

@end

 

EnterAmountViewController.h file:

#import< UIKit/UIKit.h>

//delegate to return amount entered by the user

/*This is the delegate declaration. For our delegate we only have one method which will be sending back to our root view controller an NSInteger which we will get from the user. */

@protocol EnterAmountDelegate <NSObject>

-(void)amountEntered:(NSInteger)amount;

@end

@interface EnterAmountViewController : UIViewController {

IBOutlet UITextField *amountTextField;

id<EnterAmountDelegate> delegate;

}

-(IBAction)cancelPressed;

-(IBAction)savePressed;

@property(nonatomic,assign)id delegate;

@end

 

EnterAmountViewController.m file:

#import "EnterAmountViewController.h"

@implementation EnterAmountViewController

@synthesize delegate;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

[super viewDidLoad];

amountTextField.text = @"";

[amountTextField becomeFirstResponder];

}

-(IBAction)cancelPressed {

//[self dismissViewControllerAnimated:YES completion: ];

[self dismissModalViewControllerAnimated:YES];

}

-(IBAction)savePressed {

//Is anyone listening

if([delegate respondsToSelector:@selector(amountEntered:)])

{

//send the delegate function with the amount entered by the user

[delegate amountEntered:[amountTextField.text intValue]];

}

[self dismissModalViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview.

[super didReceiveMemoryWarning];

// Release any cached data, images, etc. that aren't in use.

}

- (void)viewDidUnload {

[super viewDidUnload];

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (void)dealloc {

[super dealloc];

}

@end

Now Run the application:

at first click on the ChangeAmount button and enter any amount: like here:

 and after click on Save Button, you will see where the amount was 0 on the first screen now it is changed, this was possible with the help of delegate method. (see the result below)


Greate Artical

By ashish srivastava on   one year ago
Thanks it artical is very useful

Don't want to miss updates? Please click the below button!

Follow MindStick