ios - Multiple delegates for one object? (follow-up) -
on question multiple delegates per 1 object? 1 of answers came interesting solution (at least naive eyes) : creating "delegate splitter" allows object (in case uiscrollview) have multiple delegates (in case uiscrollviewdelegate).
the code 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 { (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 code creates retain cycles, , unlike normal delegate, can't declare
@property (assign) delegatesplitter *splitter;
it seem "better" solution wrapper. there anyway avoid retain cycle ?
how many delegates going ever need, make property 3 of them , if have need more need radically redesign app...
a better approach have delegate each activity, view delegate, data source, , asynchronous network delegate, etc... if end being same object, cares... work.
Comments
Post a Comment