Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/120.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c NSNotification在超类中观察到,并在超类和子类中处理_Objective C_Ios_Inheritance_Nsnotifications_Deterministic - Fatal编程技术网

Objective c NSNotification在超类中观察到,并在超类和子类中处理

Objective c NSNotification在超类中观察到,并在超类和子类中处理,objective-c,ios,inheritance,nsnotifications,deterministic,Objective C,Ios,Inheritance,Nsnotifications,Deterministic,我有一个类ParentClass,它观察一个通知。ParentClass处理通知子类继承父类并处理通知发送通知的顺序是否确定? 换句话说,ParentClass是否总是在ChildClass之前处理通知,反之亦然?这取决于实例化哪些类以及如何形成实际对象。它还取决于子类是否调用super进行处理。否则,正如NSNotificationCenter的文档所说,接收通知的对象的顺序是随机的,并不取决于您是子类还是超类。考虑下面的样本以更好地理解:(几个例子是需要的,因为你的解释还不完全清楚): 示例

我有一个类
ParentClass
,它观察一个通知。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

通知操作方法必须有一个参数,即通知对象。@JoshCaswell,这是真的吗?我认为,如果在注册时省略选择器名称后的冒号,则不需要该参数。我现在还不能测试…@Josh Caswell nope。如果您根据需要声明一个参数较少的方法,那么这不是问题。由于C函数调用约定,调用时参数位于堆栈顶部,函数可以逐个弹出参数,直到“参数用完”。因此,唯一真正的问题是使用的参数超过了可能的数量。“由
notificationSelector
指定的方法必须有一个且只有一个参数(一个
NSNotification
的实例)。@matt如果没有呢?因为在这种情况下,你不会对论点做任何事。。。(我知道我们必须按照医生说的去做,但即便如此,这也是可能的,虽然不优雅,但仍然有效)。