简体   繁体   English

用于超级类调用的responsToSelector

[英]respondsToSelector for super class invocation

I have the following method: 我有以下方法:

- (void) someMethod
{
    if ([super respondsToSelector:@selector(someMethod)])
    {
        [super performSelector:@selector(someMethod)
                    withObject:nil];
    }
}

someMethod does not exist on superclass. someMethod在超类上不存在。 as i understand, if there is no such method, runtime will ask the next responder in chain for such method till the NSObject class. 据我了解,如果没有这样的方法,运行时将向链中的下一个响应者询问这种方法,直到NSObject类。 And i was sure, that if statement will return NO. 而且我确信,if语句将返回否。

Statement return YES. 语句返回YES。 After that it performs selector without crash. 之后,它执行选择器而不会崩溃。 As result - infinite recursion. 结果-无限递归。

so, i have two questions: 所以,我有两个问题:

  1. Why [super respondsToSelector:@selector(someMethod)] returns YES ? 为什么[super respondsToSelector:@selector(someMethod)]返回YES?
  2. Why [super performSelector:@selector(someMethod) withObject:nil] does not crash with error 'does not responds to selector' ? 为什么[super performSelector:@selector(someMethod) withObject:nil]不会因错误“不响应选择器”而崩溃?

I think i've missed something essential. 我想我已经错过了一些必不可少的东西。 Please, help. 请帮忙。

Yes, you missed something essential as you suggest. 是的,您错过了您所建议的重要内容。 From the documentation for respondsToSelector: 从responsToSelector的文档中respondsToSelector:

You cannot test whether an object inherits a method from its superclass by sending respondsToSelector: to the object using the super keyword. 您无法通过使用super关键字向对象发送respondsToSelector:来测试对象是否从其超类继承方法。 This method will still be testing the object as a whole, not just the superclass's implementation. 此方法仍将测试整个对象,而不仅仅是超类的实现。 Therefore, sending respondsToSelector: to super is equivalent to sending it to self . 因此,向super发送respondsToSelector:等同于将其发送给self Instead, you must invoke the NSObject class method instancesRespondToSelector: directly on the object's superclass, as illustrated in the following code fragment. 相反,您必须直接在对象的超类上调用NSObject类方法instancesRespondToSelector: :,如以下代码片段所示。

if( [MySuperclass instancesRespondToSelector:@selector(aMethod)] )
{
   // invoke the inherited method
   [super aMethod];
}

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM