My Connections

Business card

Friday, September 3, 2010

How to create own delegates..... (Protocol methods)

if u want to update any variable or call any method of any class for Eg. Class A). of your project while the control is working in any other class(for Eg. Class B), then you can do it by creating your own delegate/protocol in calling class, and Declare that method in that protocol n define that method in called class.... to elaborate lets see the code.....


Calling.h //First Class

@protocol myDelegate [NSObject]
@optional
- (void) doIt;
@end

@interface Calling :
UIViewController {

id [
myDelegate] delegate;
}

@property(nonatomic, retain) id
[myDelegate] delegate;

@end




Calling.m

#import " Calling.h"

#import " Called.h "

@implementation Calling

@synthesize delegate;

- (void)viewDidLoad {
[super viewDidLoad];

[delegate hideUnhideMenu];
}

@end




Called.h // Class B

@interface Called : UIViewController
[myDelegate] {

}

@end




Called.m

#import " Called.h"

@implementation Called

- (void)viewDidLoad {
[super viewDidLoad];

Calling* obj = [[Calling alloc] init];
obj.delegate = self;
}

- (void)hideUnhideMenu {

//Do your updation here.
}

@end


NOTE: please replace "[" type of brackets with "<". 



for more details about this post click here

1 comment:

  1. property attributes for delegate should be assign. By using retain you are creating retain cycle that will cause memory leak.

    ReplyDelete