x = [self.delegate.parentDelegate method_I_want_to_call];
가장 좋은 방법은 self.delegate
에 프로토콜 메소드를 호출하고 그 클래스 호출에게 parentDelegate의 방법을 가지고있다. 그렇게하면 코드가 더 캡슐화됩니다. 또는 currentClassDelegate
프로토콜에 parentDelegate
속성을 추가 할 수 있습니다.
그러나 당신이 당신이 설명하는 방법을 할 수있는 좋은 이유가있는 경우, 다음이 작동합니다
// Import whatever class will be used for self.delegate
#import "MarcusDelegate.h"
...
// First we make sure it's safe to cast self.delegate to MarcusDelegate
if ([self.delegate isKindOfClass:[MarcusDelegate class]]) {
id parentDelegate = [(MarcusDelegate *)self.delegate parentDelegate];
if ([parentDelegate respondsToSelector:@selector(method_I_want_to_call)]) {
[parentDelegate method_I_want_to_call];
} else {
NSLog(@"WARNING: self.delegate.parentDelegate can't handle method_I_want_to_call!");
}
} else {
NSLog(@"WARNING: self.delegate is not a MarcusDelegate object!");
}
이 권장되는 방법이 아닌 이유 당신은 볼 수 있습니다. 그것은 프로토콜로 프로그래밍의 유연성을 파괴합니다. self.delegate
에 다른 클래스가 설정되어 있으면 코드가 중단되지 않아야합니다.
이 너무 작동하지만, 프로토콜 프로그래밍의 유연성을 유지 :
// in the first class
[self.delegate callThatMethodOnParent];
// then in the delegate class
- (void)callThatMethodOnParent
[self.delegate method_I_want_to_call];
}
또는 당신이 프로토콜의 척 막을 수 : "컴파일러가 불평"
@property (nonatomic, weak) MarcusDelegate *delegate;
당신이 무엇을 의미합니까 여기에서 가장 큰 문제는 'x'가 약한 변수이지만이 설명에서 알기가 어렵다는 것입니다. –
@RobNapier가 질문에 추가되었습니다. – Marcus
이것은'currentClassDelegate' 프로토콜이'parentDelegate'를 속성으로 정의하지 않는다고 불평하고 있습니다. 약점과 관련이 없습니다. –