是否可以从代表处调用原始代表?

时间:2015-01-30 04:44:35

标签: objective-c macos cocoa delegates

出于好奇,是否可以在自定义委托实现中调用原始委托方法实现。比如[super delegateMethod];或者这是不可能的。在某些情况下,如果满足某些条件,则可以向行为添加自定义项。提前谢谢!

1 个答案:

答案 0 :(得分:1)

是的,这可以通过一个包装器对象来实现,该对象拦截消息并将它们转发给另一个委托对象。下面的类在将它(以及任何其他委托方法调用)转发给另一个UIScrollViewDelegate之前拦截对scrollViewDidScroll:方法的调用。

@import UIKit;

@interface ScrollHandler : NSObject <UIScrollViewDelegate>
- (instancetype)initWithScrollViewDelegate:(id<UIScrollViewDelegate>)delegate;
@end

@implementation ScrollHandler {
    id<UIScrollViewDelegate> _scrollViewDelegate;
}

- (instancetype)initWithScrollViewDelegate:(id<UIScrollViewDelegate>)delegate {
    self = [super init];
    if (self) {
        _scrollViewDelegate = delegate;
    }
    return self;
}

// Intercept specific method invocations:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // Implement custom behavior here before forwarding the invocation to _scrollViewDelegate
    [_scrollViewDelegate scrollViewDidScroll:scrollView];
}

// Forward unintercepted method invocations:

- (BOOL)respondsToSelector:(SEL)selector
{
    // Ask _scrollViewDelegate if it responds to the selector (and ourself as well)
    return [_scrollViewDelegate respondsToSelector:selector] || [super respondsToSelector:selector];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    // Forward the invocation to _scrollViewDelegate
    [invocation invokeWithTarget:_scrollViewDelegate];
}

@end

使用示例:

_scrollView = [[ScrollHandler alloc] init];
_scrollController = [[ScrollHandler alloc] initWithScrollViewDelegate:self];
_scrollView.delegate = _scrollController;