Well, you are working with ObjC, so you will need to exercise some restraint:
@protocol MONAbstractDataProvider @optional - (void)anOptionalMethod; @end @protocol MONDataProviderA < MONAbstractProvider > @required - (void)onePossibleMethod; @end @protocol MONDataProviderB < MONAbstractProvider > @required - (void)anotherPossibleMethod; @end
In this case, you will need to run the confromsToProtocol: test on the callsite site, not the respondsToSelector: test for onePossibleMethod and anotherPossibleMethod . Then you pass MONAbstractDataProvider around. This may introduce some type safety if you remember the rules, but it is really a little better than the usual approach.
Thus, the client side will look like this:
- (void)update:(NSObject<MONAbstractDataProvider>*)provider { if ([provider conformsToProtocol:@protocol(MONDataProviderA)]) { [(NSObject<MONDataProviderA>*)protocol onePossibleMethod]; } else if ([provider conformsToProtocol:@protocol(MONDataProviderB)]) { [(NSObject<MONDataProviderB>*)provider anotherPossibleMethod]; } else { assert(0 && "rule broken"); } }
This, of course, assumes that the client is aware of all derivatives.
Instead, you can choose a simpler singular approach if they are both void :
@protocol MONAbstractDataProvider @required - (void)performPossibleMethod; @optional - (void)anOptionalMethod; @end
justin
source share