On the question Multiple delegates per one object? one of the answers came up with interesting solution (at least for my naive eyes) : creating a "delegate splitter" that allows an object (in this case UIScrollView) to have multiple delegates (in this case UIScrollViewDelegate).
The code is as follows:
@interface DelegateSplitter : NSObject
-(void)addDelegate:(id)delegate;
-(void)addDelegates:(NSArray*)array;
@end
@interface DelegateSplitter()
@property NSMutableSet *delegates;
@end
@implementation DelegateSplitter
-(id)init
{
self = [super init];
_delegates = [NSMutableSet set];
return self;
}
-(void)addDelegate:(id)delegate
{
[_delegates addObject:delegate];
}
-(void)addDelegates:(NSArray *)array
{
[_delegates addObjectsFromArray:array];
}
-(void)forwardInvocation:(NSInvocation *)anInvocation
{
for (id delegate in _delegates)
{
if([delegate respondsToSelector:anInvocation.selector])
{
[anInvocation invokeWithTarget:delegate];
}
}
}
- (NSMethodSignature*) methodSignatureForSelector: (SEL) selector
{
NSMethodSignature *our = [super methodSignatureForSelector:selector];
NSMethodSignature *delegated = [[_delegates anyObject]
methodSignatureForSelector:selector];
return our ? our : delegated;
}
- (BOOL) respondsToSelector: (SEL) selector
{
return [[_delegates anyObject] respondsToSelector:selector];
}
The problem with this code is that it creates retain cycles, and unlike a normal delegate, you can't declare it as
@property (assign) DelegateSplitter *splitter;
It does seem however a "better" solution than a wrapper. So is there anyway to avoid the retain cycle ?