开发者

Objective-C and use of SEL/IMP

Another question of mine about optimizing Obje开发者_运维知识库ctive C programs inspired the following: does anyone have a short example using SEL and IMP when theMethod has two (or more) integers for input?


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?


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.


Here is another possible alternative. This avoids the crash but stubbing doesn't work.

- (void)setUp
{
   [super setUp];

   [self addSelector@selector(firstName) toClass:[User class]];
   [self addSelector@selector(lastName) toClass:[User class]];
}

- (void)addSelector:(SEL)selector toClass:(Class)class
{
    NSString *uniqueName = [NSString stringWithFormat:@"%@-%@", NSStringFromClass(class), NSStringFromSelector(selector)];
    SEL sel = sel_registerName([uniqueName UTF8String]);
    IMP theImplementation = [class methodForSelector:sel];
    class_addMethod(class, selector, theImplementation, "v@:@");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜