Reputation: 4373
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 ?
Upvotes: 0
Views: 252
Reputation: 14549
how many delegates are you going to ever need, just make a property for 3 of them and if you have need for more then you need to radically redesign your app...
a much better approach is to have a delegate for each activity, a view delegate, a data source, and some asynchronous network delegate, etc... if they end up being the same object, who cares... it will just work.
Upvotes: 1