【发布时间】:2010-04-16 02:25:48
【问题描述】:
我关于optimizing Objective C programs 的另一个问题启发了以下内容:当theMethod 有两个(或更多)整数用于输入时,是否有人有一个使用SEL 和IMP 的简短示例?
【问题讨论】:
-
你能提供更多细节吗?我不确定你所说的 SEL 和 IMP 是什么意思。
-
是的,你到底想做什么?
标签: objective-c
我关于optimizing Objective C programs 的另一个问题启发了以下内容:当theMethod 有两个(或更多)整数用于输入时,是否有人有一个使用SEL 和IMP 的简短示例?
【问题讨论】:
标签: objective-c
这是一个good tutorial,用于获取当前的 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) = ...
然后您可以像这样调用 IMP:
theImplementation(self, theSelector, 3, 5);
通常没有理由需要 IMP,除非你正在做严肃的巫术 - 你有什么具体想做的事情吗?
【讨论】:
感谢 eman,现在我已经完成了这项工作,我可以再添加一个示例:
SEL cardSelector=@selector(getRankOf:::::::);
IMP rankingMethod=[eval methodForSelector:cardSelector];
rankingMethod(eval, cardSelector, 0, 1, 2, 3, 4, 5, 6);
我不需要它来做任何有用的事情,我只需要满足我的好奇心!再次感谢。
【讨论】:
这是另一种可能的选择。这样可以避免崩溃,但存根不起作用。
- (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@:@");
}
【讨论】: