Skip to content

Instantly share code, notes, and snippets.

@NorrinRadd
Created May 28, 2013 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NorrinRadd/5664605 to your computer and use it in GitHub Desktop.
Save NorrinRadd/5664605 to your computer and use it in GitHub Desktop.
Before calling an optional protocol method, it is good to check if the delegate has implemented the methods. This is usually done using the following pattern: if (_delegate && [_delegate.respondsToSelector:@selector(method1)]) { // Do your thing } Turns out that some days ago, I faced a better way to do this kind of check by creating a struct an…
// TestClass.h
#import <Foundation/Foundation.h>
@protocol TestProtocol <NSObject>
@optional
- (void) testProtocolMethod;
@end
@interface TestClass: NSObject
{
// Struct that will hold the methods that the delegate implements
struct {
unsigned int respondsToTestProtocolMethod: 1;
} _delegateFlags;
}
@property (nonatomic, weak) id<TestProtocol> delegate;
- (id)init;
- (void)doSomething;
// TestClass.m
#import "TestClass.h"
@implementation TestClass
@synthesize delegate=_delegate;
// Init methods...
- (void)setDelegate:(id<TestProtocol>)delegate
{
// Sets the delegate and populates the flags struct
_delegate = delegate;
_delegateFlags.respondsToTestProtocolMethod = [_delegate respondsToSelector:@selector(testProtocolMethod)];
}
- (void)doSomething
{
// We can check only the flag instead of calling respondsToSelector
(if _delegateFlags.respondsToTestProtocolMethod) {
// Do your thing and be happy
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment