【问题标题】:NSInvocation with an enum?带有枚举的 NSInvocation?
【发布时间】:2016-08-25 15:40:35
【问题描述】:

------------ 编辑 -------------

TL;DR:

似乎我错误地使用了 NSInvocation 类(缺乏指针知识)。

使用它们的方式是这样的(作品):

NSString *str = @"string";
UIControlState state = UIControlStateNormal;
[invocation setArgument: &str atIndex: 2];
[invocation setArgument: &state atIndex: 3];

---------------- 原始问题 ---------

可以setArgument:atIndex: 使用枚举参数吗?

请参阅以下示例(不起作用):

UIButton *btn = ...;
SEL selector = @selector(setTitle:forState:);
NSInovcation *invocation = [NSInovcation invocationWithMethodSignature: [btn methodSignatureForSelector: selector]];
[invocation setSelector: selector];
[invocation setArgument: @"Test" atIndex: 2];

//Nothing happens
UIControlState state = UIControlStateNormal;
[invocation setArgument: &state atIndex: 3];

//Runtime error (the pointer is NULL)
UIControlState *state = UIControlStateNormal;
[invocation setArgument: state atIndex: 3];

//No errors but no effect
int state2 = 0;
[invocation setArgument: &state atIndex: 3];

//Compile error (casting)
[invocation setArgument: @(UIControlStateNormal) atIndex: 3];
//Runtime EXC_BAD_ACCESS
[invocation setArgument: (void *)@(UIControlStateNormal) atIndex: 3];

...
[invocation invokeWithTarget: btn];

奇怪的是(或不是),它确实适用于performSelector:...

[btn performSelector: selector withObject: @"Testing" withObject:@(UIControlStateNormal)];

我不确定我是否以正确的方式使用 NSInovcation。有人想详细说明吗?

【问题讨论】:

  • 使用@(...) 将枚举值包装在NSNumber 中。澄清你所说的“不起作用”是什么意思。编译错误?运行时错误?意外行为?具体一点。
  • 转换的编译时间错误,将其转换为void * 不会给出任何错误,它什么也不做。我认为它的行为不像 performSelector 那样。
  • 我没有使用过 NSInvocation,但是,您尝试调用的选择器只有 2 个参数。我看到您正在使用索引:2 和 3。它们不应该是 0 和 1 吗?
  • 按照 NSInvocation 文档,参数 0 和 1 是 self_cmd
  • 嗯,有道理。我忘了那些是隐含的。

标签: ios cocoa cocoa-touch enums nsinvocation


【解决方案1】:

试试这个:

NSString *test = @"Test";
[invocation setArgument: &test atIndex: 2];

UIControlState state = UIControlStateNormal;
[invocation setArgument: &state atIndex: 3];

【讨论】:

  • 见上文,作为我的问题的一部分,我已经添加了一个答案,但感谢您做出正式的回答。
猜你喜欢
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多