2

NSNotification을 준수하는 클래스 ParentClass이 있습니다. ParentClass가 알림을 처리합니다. ChildClass은 ParentClass를 상속하고 알림도 처리합니다. 알림이 결정적으로 전달되는 순서는 무엇입니까?수퍼 클래스에서 NSNotification을 관찰하고 슈퍼 및 하위 클래스에서 처리합니다.

즉, ParentClass는 항상 ChildClass 이전에 알림을 처리합니까, 그 반대의 경우도 마찬가지입니까?

답변

2

실제 개체를 형성하는 방법과 인스턴스화되는 클래스에 따라 다릅니다. 또한 서브 클래스가 처리를 위해 super를 호출하는지 여부에 달려 있습니다. 그렇지 않으면 NSNotificationCenter의 문서에서 알 수 있듯이 알림을받는 객체의 순서는 무작위이며 하위 클래스 또는 수퍼 클래스에 종속되지 않습니다. 더 나은 이해를 위해 다음과 같은 샘플을 고려 : (당신의 해설이 완전히 명확하지 않다으로 몇 가지 예제가 필요) :

예 1 : 두 개의 서로 다른 개체

ParentClass *obj1 = [[ParentClass alloc] init]; 
ChildClass *obj2 = [[ChildClass alloc] init]; 
// register both of them as listeners for NSNotificationCenter 
// ... 
// and now their order of receiving the notifications is non-deterministic, as they're two different instances 

예 2 : 서브 클래스는 슈퍼

@implementation ParentClass 

- (void) handleNotification:(NSNotification *)not 
{ 
    // handle notification 
} 

@end 

@ipmlementation ChildClass 

- (void) handleNotification:(NSNotification *)not 
{ 
    // call super 
    [super handleNotification:not]; 
    // actually handle notification 
    // now the parent class' method will be called FIRST, as there's one actual instace, and ChildClass first passes the method onto ParentClass 
} 

@end 
를 호출
+0

알림 작업 메서드에는 하나의 매개 변수 인 알림 개체가 있어야합니다. –

+1

@ JoshCaswell, 그게 사실입니까? 나는 당신이 당신이 매개 변수를 필요로하지 않았다는 것을 등록 할 때 당신이 선택자 이름 다음에 콜론을 생략한다면 그것을 생각했다. 나는 지금 당장 그것을 테스트 할 수 없다 ... –

+0

@ Josh Caswell nope. 필요한만큼 인자가 적은 메소드를 선언하면 문제가되지 않습니다. C 함수 호출 규칙 때문에 호출 할 때 매개 변수는 스택의 맨 위에 있고 함수는 "인수가 없어 질 때까지 하나씩 함수를 호출 할 수 있습니다. 유일한 진실한 문제는 가능한 한 많은 논증을 사용할 때입니다. –

관련 문제