我有ParentClass
一个观察 NSNotification 的类。ParentClass 处理通知。ChildClass
继承 ParentClass 并处理通知。发送通知的顺序是否具有确定性?
换句话说,ParentClass 是否总是在 ChildClass 之前处理通知,反之亦然?
我有ParentClass
一个观察 NSNotification 的类。ParentClass 处理通知。ChildClass
继承 ParentClass 并处理通知。发送通知的顺序是否具有确定性?
换句话说,ParentClass 是否总是在 ChildClass 之前处理通知,反之亦然?
这取决于实例化哪些类以及如何实例化实际对象。还要看子类是否调用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:子类调用 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