【问题标题】:Objective-C and use of SEL/IMPObjective-C 和 SEL/IMP 的使用
【发布时间】:2010-04-16 02:25:48
【问题描述】:

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

【问题讨论】:

  • 你能提供更多细节吗?我不确定你所说的 SEL 和 IMP 是什么意思。
  • 是的,你到底想做什么?

标签: objective-c


【解决方案1】:

这是一个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:您需要转换该返回值: void (* theImplementation)(id,SEL,int,int) = (void (*)(id,SEL,int,int))[ self methodForSelector:theSelector];
  • @Jason Coco-如果我错了,请纠正我,但我认为 IMP 的类型定义为 (id, SEL, ...),所以没关系(尽管它不是类型安全的,但如果您需要类型安全,您可能不应该使用 IMP)。
  • 你是对的,因为这个方法是无效的,它是可以的,但是在许多其他情况下你会得到错误。你/需要/施放可能太强了,你/应该总是施放/可能更正确;)-但考虑到这个问题本身,我的猜测是 OP 可能/不应该/使用 IMP。
  • @Jason Coco:好点,没想到这一点(更新示例)。
  • 非常感谢您的回复。你绝对正确,我的代码绝对不需要这个,但我很好奇。我还认为它可能更普遍,因为我无法为多个输入获得正确的语法。
【解决方案2】:

感谢 eman,现在我已经完成了这项工作,我可以再添加一个示例:

SEL cardSelector=@selector(getRankOf:::::::);

IMP rankingMethod=[eval methodForSelector:cardSelector];

rankingMethod(eval, cardSelector, 0, 1, 2, 3, 4, 5, 6);

我不需要它来做任何有用的事情,我只需要满足我的好奇心!再次感谢。

【讨论】:

【解决方案3】:

这是另一种可能的选择。这样可以避免崩溃,但存根不起作用。

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

【讨论】:

    猜你喜欢
    • 2012-07-31
    • 2010-12-20
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多