Wednesday, 27 November 2013

Create your own Objective-C Delegate Protocol

To create your own custom delegate protocol, you need to modify the header file for the selected class to then add the @protocol declaration, a delegate @property, and declare the methods that delegates can implement:

Please note; this tutorial is written on the understanding that you have basic to moderate knowledge in the iOS Application Development language: Objective-C. If this is not the case then I suggest that you read Objective-C book to further develop your knowledge and ensure you can successfully follow on with this tutorial.


// YourViewController.h: 

#import <UIKit/UIKit.h>

@protocol YourProtocolName

@interface YourViewController: UIViewController

@property (nonatomic, weak)id<YourProtocolName> delegate;
@end
@protocol YourProtocolName <NSObject>

@required

-(void)requiredDelegateMethod;

@optional
-(void)optionalDelegateMethodOne;
-(void)optionalDelegateMethodTwo:(NSString *)withArgument;


@end 
// end of delegate protocol


Next, In the implementation file, anytime you want to call the delegate method, you first need to check and see if the delegate is set, and then if it responds to the selector. Once this is checked, then you can call the method, for this we are going to use an if statement:
if (self.delegate && [self.delegate respondsToSelector:@selector(optionalDelegateMethodOne)])
{
    [self.delegate optionalDelegateMethodOne];
}

Now for classes you want to conform to your new protocol, include the header file and delegate protocol in the @interface:
#include "YourViewController.h"  
// needed to include the @delegate protocol info


@interface FavoritesViewController : UIViewController <YourProtocolName>


Finally, any required delegate methods must then be implemented in your class’s @implementation file.

I thought it worth while to explain that the first @protocol line in the header is only needed if the actual protocol comes after the @interface@end code.
So this works as well





// YourViewController.h:

#import <UIKit/UIKit.h>

@protocol YourProtocolName <NSObject>
@required
-(void)requiredDelegateMethod;

@optional
-(void)optionalDelegateMethodOne;
-(void)optionalDelegateMethodTwo:(NSString *)withArgument;

@end // end of delegate protocol

@interface YourViewController: UIViewController

@property (nonatomic, weak) id<YourProtocolName> delegate;



@end

No comments:

Post a Comment