objective-c

Objective-C and use of SEL/IMP


Another question of mine about optimizing Objective C programs inspired the following: does anyone have a short example using SEL and IMP when theMethod has two (or more) integers for input?


Solution

  • Here's a good tutorial for getting the current IMP (with an overview of IMPs). A very basic example of IMPs and SELs is:

    - (void)methodWithInt:(int)firstInt andInt:(int)secondInt { NSLog(@"%d", firstInt + secondInt); }
    
    SEL theSelector = @selector(methodWithInt:andInt:);
    typedef void (*MyMethodImplementation)(id, SEL, int, int);
    MyMethodImplementation theImplementation = (MyMethodImplementation)[self methodForSelector:theSelector];
    

    You could then invoke the IMP like so:

    theImplementation(self, theSelector, 3, 5);
    

    There's usually no reason to need IMPs unless you're doing serious voodoo--is there something specific you want to do?