Objective-C和SEL/IMP的使用

SK9*_*SK9 24 objective-c

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

sho*_*sti 50

这是获取当前IMP 的一个很好的教程(概述了IMP).IMP和SEL的一个非常基本的例子是:

- (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) = ...
Run Code Online (Sandbox Code Playgroud)

然后您可以像这样调用IMP:

theImplementation(self, theSelector, 3, 5);
Run Code Online (Sandbox Code Playgroud)

除非你正在做严肃的伏都教,否则通常没有理由需要IMPs - 你有什么特别的想做吗?

  • @eman:你需要转换那样的返回:void(*theImplementation)(id,SEL,int,int)=(void(*)(id,SEL,int,int))[self methodForSelector:theSelector]; (3认同)
  • 你是对的,因为这个方法是无效的,但是你可以在许多其他实例中得到错误.你/需要/施放可能太强大,你/应该总是施放/可能更正确;) - 但是考虑到这个问题本身,我的猜测是OP可能/不应该/正在使用IMP. (3认同)