2

ParentClassNSNotificationを監視するクラスがあります。ParentClassが通知を処理します。ChildClassParentClassを継承し、通知も処理します。通知が配信される順序は決定論的ですか?

言い換えると、ParentClassは常にChildClassの前に通知を処理しますか、またはその逆ですか?

4

1 に答える 1

2

これは、インスタンス化されるクラスとその方法によって異なり、実際のオブジェクトを形成します。また、サブクラスが処理のためにsuperを呼び出すかどうかにも依存します。それ以外の場合、NSNotificationCenterのドキュメントに記載されているように、通知を受け取るオブジェクトの順序はランダムであり、サブクラスかスーパークラスかに依存しません。理解を深めるために、次のサンプルを検討してください。(説明が完全に明確ではないため、いくつかの例が必要です)。

例1:2つの異なるオブジェクト

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:サブクラスがsuperを呼び出す

@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
于 2012-01-19T21:25:57.980 に答える