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?
+6
A:
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:);
IMP theImplementation = [self methodForSelector:theSelector];
//note that if the method doesn't return void, you have to explicitly typecast the IMP, e.g. int(* foo)(id, SEL, int, int) = ...
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?
eman
2010-04-16 02:39:21
@eman: you need to cast that return so: void (* theImplementation)(id,SEL,int,int) = (void (*)(id,SEL,int,int))[self methodForSelector:theSelector];
Jason Coco
2010-04-16 02:49:54
@Jason Coco-Correct me if I'm wrong, but I think IMP is typedef'd as (id, SEL, ...), so it shouldn't matter (although it's not typesafe, but if you need typesafety, you probably shouldn't be using IMPs).
eman
2010-04-16 02:59:02
@eman: You are right, since this method is void it is ok, but you will get errors in many other instances. You /need/ to cast was probably too strong, you /should always cast/ is probably more correct ;)--but given this question itself, my guess is that the OP probably /should not/ be using IMP either.
Jason Coco
2010-04-16 03:15:33
@Jason Coco: Good point, didn't think of that (updated example).
eman
2010-04-16 03:28:39
Many thanks for the replies. You're absolutely correct that I definitely do not need this for my code but I was curious. I also thought it may be of interest more generally as I couldn't get the syntax right for more than one input.
SpecialK
2010-04-17 03:01:12
A:
Now that I have this working thanks to eman, I can add yet another example:
SEL cardSelector=@selector(getRankOf:::::::);
IMP rankingMethod=[eval methodForSelector:cardSelector];
rankingMethod(eval, cardSelector, 0, 1, 2, 3, 4, 5, 6);
I don't need this for anything useful, I just needed to satisfy my curiosity! Thank you again.
SpecialK
2010-04-21 11:09:34
Another good link on optimising Objective-C ishttp://www.mulle-kybernetik.com/artikel/Optimization/opti-3-imp-deluxe.html
SpecialK
2010-04-22 06:41:21