0
關於問題Multiple delegates per one object?其中一個答案提出了一個有趣的解決方案(至少對於我的天真的眼睛):創建一個「委託拆分器」,允許一個對象(在這種情況下,UIScrollView)有多個委託在這種情況下UIScrollViewDelegate)。一個對象的多個代表? (後續)
的代碼如下:
@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];
}
這段代碼的問題是,它創建保留週期,而不像一個正常的委託,你不能將它聲明爲
@property (assign) DelegateSplitter *splitter;
它似乎不過是比包裝更「更好」的解決方案。那麼無論如何要避免保留週期?