Monday, August 19, 2013

Objective-C: Delegate Protocols



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

#import <UIKit/UIKit.h>

@protocol MyProtocolName

@interface MyViewController: UIViewController

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

@end

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

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

@end // end of delegate protocol
In the implementation file, anytime you want to call a delegate method, first check to see if the delegate is set, and if it responds to the selector. Then call the method:
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 "MyViewController.h"  // needed to include the @delegate protocol info

@interface FavoritesViewController : UIViewController <MyProtocolName> 
Any required delegate methods must then be implemented in your class's @implementation file.

No comments:

Post a Comment