Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to catch all selector calls and redirect them at runtime

Tags:

objective-c

I want to do something a little hacky.

When we try and call a method on a class where isn't defined we usually get an error, e.g.

// We get a undefined selector callback
[myClass someUndefinedMethod];

I want to add something into MyClass that catches all these undefined method calls and deals with it. Is this possible?

I want something like this, but which will intercept all method calls:

@implementation MyClass

    - (void) performSelector(SEL):selector {

          // Check if the method exists
          if (![self respondsToSelector:selector]) {
              // Handle unimplemeted selector
              NSLog(@"No method called %@", selector);
          } 

          // Otherwise proced as normal
          else {
              [super performSelector:selector];
          }
    }

@end
like image 375
Robert Avatar asked Dec 16 '11 12:12

Robert


3 Answers

Why not just override the doesNotRecognizeSelector: method on NSObject (assuming you're inheriting from it, which you should be)?

like image 168
paulbailey Avatar answered Nov 04 '22 19:11

paulbailey


Override method: -[MyClass doesNotRecognizeSelector:] and call whatever you want.

This is what NSManagedObject is doing to get/set core data properties.

like image 32
Sulthan Avatar answered Nov 04 '22 19:11

Sulthan


I'm not clear whether you are trying to intercept messages sent to a class or to an instance of a class. In any case perhaps looking into / searching on the topics of 'message forwarding' and 'forwarding messages'. Also see NSObject's forwardInvocation and the section of Apple's runtime pgmg guide on message forwarding http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html

These got me to the answer I was looking for and I did not see them mentioned elsewhere on this question.

like image 1
Art Swri Avatar answered Nov 04 '22 18:11

Art Swri