Friday, March 18, 2011

Use of Protocols to create and work on own delegates

Delegates are very useful to control transfer within the array of view controllers in app manually. Using delegates you can manage the control flow very well.

here is small example of own delegates....

1. Create a protocol class.... (.h only)



SampleDelegate.h


#import


@protocol SampleDelegate
@optional

#pragma Home Delegate

-(NSString *)getViewName;

@end



2. Import above protocol class in the class whom you want to make delegate of another class. Here in my ex. I m using AppDelegate to make delegate of The HomeViewController's Object.

also add above DelegateName in Delegate Reference < >


ownDelegateAppDelegate.h

#import "SampleDelegate.h"

@interface ownDelegateAppDelegate : NSObject <UIApplicationDelegate, SampleDelegate> {

}


ownDelegateAppDelegate.m

//setDelegate of the HomeViewController's object as
[homeViewControllerObject setDelegate:self];

//add this delegate method definition
-(NSString *)getViewName
{
    return @"Delegate Called";
}




HomeViewController.h

#import
#import "SampleDelegate.h"

@interface HomeViewController : UIViewController {
    
    id<SampleDelegate>delegate;
}

@property(readwrite , assign) id<SampleDelegate>delegate;

@end



HomeViewController.h

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    
    UILabel *lblTitle = [[UILabel alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    lblTitle.text = [delegate getViewName];
    lblTitle.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:lblTitle];
}


 or download above source code from here.



1 comment: