Tuesday, June 1, 2010

How to create our own delegate for any class in iPhone?

Today I am going to show you how can we create our delegates for class using protocols.It has been always a bit tough for beginners to see how delegation works and how it can be cretaed. I am trying to explain this in a very lucid way. Just follow the steps.







1. Open xcode


2. Create new project with name "MyDelegateForClass"

3. Create new class MYClass

4.Define @protocol MyClassDelegate; at the top in the interface file.

5. Define a delegate in interface
id <myclassdelegate> myDelegate;

6.create a property for myDelegate.
id <myclassdelegate> myDelegate;

we normally do not retain delegates to avoid the retain cycles.
7. create interface for MyClassDelegate

@protocol MyClassDelegate

-(void)myDelegateMethod;

@end

8. @synthesize myDelegate;

9.mydelegate is ready we can pass the message to myDelegate which is going to handle it.
we can pass message -(void)myDelegateMethod to myDelegate any where in @implementation MyClass, after initialization of class is over.
Let we call this in
- (void)viewDidLoad {
[super viewDidLoad];
[myclass.myDelegate myDelegateMethod];
}
10. Now MyClass has a delegate -(void)myDelegateMethod which we can access in any other class.

11. Lets say we need to access this delegate in MyDelegateForClassViewController
what we need to do for that in the interface class of MyDelegateForClassViewController declare protocol MyClassDelegate.
#import"MyClass.h"
@interface MyDelegateForClassViewController : UIViewController<myclassdelegate> {

}

@end

12. Initialize Myclass and set its delegate to MyDelegateForClassViewController
{
//Create instance of MyClass in MyDelegateForClassViewController
MyClass *myclass = [[MyClass alloc] initWithNibName:@"MyClass" bundle:[NSBundle mainBundle]];
myclass.myDelegate = self;
[self presentModalViewController:myclass animated:NO];
[myclass release];
}



13. In @implementation MyDelegateForClassViewController
define the protocol method of MyClass
-(void)myDelegateMethod
{

//here write some code and logic
NSLog(@" This is a delegate method in MyDelegateForClassViewController");
}



This is how delegates can be created for class where we want.


you can download the source code from : source Code

what is the use of delegates hope it would have been clear now.It can be used to communicate between class.

No comments:

Post a Comment