super class 调用的 respondsToSelector
respondsToSelector for super class invocation
我有以下方法:
- (void) someMethod
{
if ([super respondsToSelector:@selector(someMethod)])
{
[super performSelector:@selector(someMethod)
withObject:nil];
}
}
someMethod 不 存在于 superclass 上。据我所知,如果没有这样的方法,运行时将向链中的下一个响应者询问这样的方法,直到 NSObject class。而且我确信,if 语句将 return 否。
声明return是的。之后它执行选择器而不会崩溃。结果 - 无限递归。
所以,我有两个问题:
- 为什么
[super respondsToSelector:@selector(someMethod)]
return 是?
- 为什么
[super performSelector:@selector(someMethod) withObject:nil]
不会因错误 'does not responds to selector' 而崩溃?
我想我错过了一些重要的东西。
请帮忙。
是的,您错过了您建议的重要内容。来自 respondsToSelector:
的文档
You cannot test whether an object inherits a method from its superclass by sending respondsToSelector:
to the object using the super
keyword. 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
. Instead, you must invoke the NSObject
class method instancesRespondToSelector:
directly on the object’s superclass, as illustrated in the following code fragment.
if( [MySuperclass instancesRespondToSelector:@selector(aMethod)] )
{
// invoke the inherited method
[super aMethod];
}
HTH
我有以下方法:
- (void) someMethod
{
if ([super respondsToSelector:@selector(someMethod)])
{
[super performSelector:@selector(someMethod)
withObject:nil];
}
}
someMethod 不 存在于 superclass 上。据我所知,如果没有这样的方法,运行时将向链中的下一个响应者询问这样的方法,直到 NSObject class。而且我确信,if 语句将 return 否。
声明return是的。之后它执行选择器而不会崩溃。结果 - 无限递归。
所以,我有两个问题:
- 为什么
[super respondsToSelector:@selector(someMethod)]
return 是? - 为什么
[super performSelector:@selector(someMethod) withObject:nil]
不会因错误 'does not responds to selector' 而崩溃?
我想我错过了一些重要的东西。 请帮忙。
是的,您错过了您建议的重要内容。来自 respondsToSelector:
You cannot test whether an object inherits a method from its superclass by sending
respondsToSelector:
to the object using thesuper
keyword. This method will still be testing the object as a whole, not just the superclass’s implementation. Therefore, sendingrespondsToSelector:
tosuper
is equivalent to sending it toself
. Instead, you must invoke theNSObject
class methodinstancesRespondToSelector:
directly on the object’s superclass, as illustrated in the following code fragment.
if( [MySuperclass instancesRespondToSelector:@selector(aMethod)] )
{
// invoke the inherited method
[super aMethod];
}
HTH