0

------------ 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?

natanavra
  • 2,100
  • 3
  • 18
  • 24
  • Using `@(...)` wraps the enum value in an `NSNumber`. Clarify what you mean by "doesn't work". Compile error? Runtime error? Unexpected behavior? Be specific. – rmaddy Aug 25 '16 at 15:43
  • Compile time error for casting, casting it to `void *` doesn't give any errors it just does nothing. I assume it does not behave like `performSelector` does. – natanavra Aug 25 '16 at 15:44
  • I haven' used NSInvocation, however, the selector you're trying to invoke only has 2 arguments. I see that you're using indexes: 2 and 3. Should they not be 0 and 1? – Jonathan Aug 25 '16 at 15:45
  • 1
    Following the NSInvocation documentation, arguments 0 and 1 are `self` and `_cmd` – natanavra Aug 25 '16 at 15:45
  • Ah ok, makes sense. I forgot those are implicit. – Jonathan Aug 25 '16 at 15:46

1 Answers1

1

try this:

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

UIControlState state = UIControlStateNormal;
[invocation setArgument: &state atIndex: 3];
Razor
  • 91
  • 1
  • 4