简体   繁体   中英

NSInvocation with an enum?

------------ EDIT -------------

TL;DR:

It seems I used the NSInvocation class incorrectly (lacking pointer knowledge).

The way to use those would be like so (Works):

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

--------------- Original Question ---------

Is it possible to setArgument:atIndex: with an enum argument?

See the following example (that doesn't work):

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];

Strangely (or not), it does work well with performSelector:... :

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

I'm not sure I'm using NSInovcation the correct way. Anyone would like to elaborate?

try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM