带有枚举的NSInvocation?

时间:2016-08-25 15:40:35

标签: ios cocoa cocoa-touch enums nsinvocation

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

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。有人想详细说明吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

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

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