Multiple delegates per one object?

后端 未结 5 2051
无人共我
无人共我 2020-12-25 14:54

I have a UIScrollView that I need to subclass and within the subclass I need to attach the UIScrollViewDelegate so I can implement the viewFo

5条回答
  •  既然无缘
    2020-12-25 15:40

    Sometimes it makes sense to attach several delegates to a scroll view. In that case you can build a simple delegation splitter:

    // Public interface
    @interface CCDelegateSplitter : NSObject
    
    - (void) addDelegate: (id) delegate;
    - (void) addDelegates: (NSArray*) delegates;
    
    @end
    
    // Private interface
    @interface CCDelegateSplitter ()
    @property(strong) NSMutableSet *delegates;
    @end
    
    @implementation CCDelegateSplitter
    
    - (id) init
    {
        self = [super init];
        _delegates = [NSMutableSet set];
        return self;
    }
    
    - (void) addDelegate: (id) delegate
    {
        [_delegates addObject:delegate];
    }
    
    - (void) addDelegates: (NSArray*) delegates
    {
        [_delegates addObjectsFromArray:delegates];
    }
    
    - (void) forwardInvocation: (NSInvocation*) invocation
    {
        for (id delegate in _delegates) {
            [invocation invokeWithTarget:delegate];
        }
    }
    
    - (NSMethodSignature*) methodSignatureForSelector: (SEL) selector
    {
        NSMethodSignature *our = [super methodSignatureForSelector:selector];
        NSMethodSignature *delegated = [(NSObject *)[_delegates anyObject] methodSignatureForSelector:selector];
        return our ? our : delegated;
    }
    
    - (BOOL) respondsToSelector: (SEL) selector
    {
        return [[_delegates anyObject] respondsToSelector:selector];
    }
    
    @end
    

    Then simply set an instance of this splitter as a delegate of the scroll view and attach any number of delegates to the splitter. All of them will receive the delegation events. Some caveats apply, for example all the delegates are assumed to be of the same type, otherwise you’ll have trouble with the naive respondsToSelector implementation. This is not a big problem, it’s easy to change the implementation to only send delegation events to those who support them.

提交回复
热议问题