1
votes

I have the following method:

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

someMethod does not exist on superclass. as i understand, if there is no such method, runtime will ask the next responder in chain for such method till the NSObject class. And i was sure, that if statement will return NO.

Statement return 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 ?
  2. Why [super performSelector:@selector(someMethod) withObject:nil] does not crash with error 'does not responds to selector' ?

I think i've missed something essential. Please, help.

1

1 Answers

4
votes

Yes, you missed something essential as you suggest. From the documentation for 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