Friday, January 24, 2014

Optional Protocol Methods

Methods in protocols are required by default but can be set to optional using the @optional directive. Here's how to implement optional delegates:

@protocol myProtocol

//@required
-(NSString *)requiredMethod:(MyCustomObject *)myObject;

@optional
-(NSString  *)optionalMethod:(MyCustomObject *)myObject;
@end  
respondsToSelector can be used to see if the optional method exists and if so, react to it.
@interface myClass : aSuperClass 
...
if ([self.delegate respondsToSelector:@selector(optionalMethod:)]) {
   myString = [self.delegate optionalMethod:self];
} else {
   myString = @"Default Value";           
}

No comments:

Post a Comment