简体   繁体   中英

Objective-C and use of SEL/IMP

关于优化Objective C程序的另一个问题启发了以下内容:当theMethod有两个(或更多)整数输入时,是否有人使用SEL和IMP的简短示例?

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?

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@:@");
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM