Created
May 28, 2013 17:43
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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