2015-01-30 3 views
0

호기심에서 벗어나 사용자 지정 위임 구현에서 원래의 위임 메서드 구현을 호출 할 수 있습니까? [super delegateMethod]처럼; 아니면 불가능합니다. 특정 조건이 충족되는 경우 동작에 사용자 지정을 추가하는 것과 같은 몇 가지 시나리오가 있습니다. 미리 감사드립니다.대리인의 원래 대리인에게 전화를 걸 수 있습니까?

답변

1

예, 메시지를 가로 채어 다른 위임 객체로 전달하는 래퍼 객체를 통해이 작업을 수행 할 수 있습니다. 다음 클래스는 scrollViewDidScroll : 메서드를 다른 UIScrollViewDelegate로 전달하기 전에 호출을 가로 챈 다음 다른 위임 메서드 호출을 다른 UIScrollViewDelegate로 전달합니다.

@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; 
+0

아 재미! 나는 다른 클래스에서 클래스를 래핑하려고 생각하지 않았지만, 그것은 많은 의미를가집니다. 고맙습니다! – CoderNinja

관련 문제