Rudolf Adamkovič
Rudolf Adamkovič

Reputation: 31486

Pointer to BOOL in Objective C

Code:

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
BOOL initial = YES;
[invocation setArgument:&initial atIndex:2];

Question:

Would it be possible to pass YES to setArgument:atIndex: without creating the temporary variable?

I was thinking that maybe there's a language construct I'm not aware of and/or constant in the runtime that is always YES that I can point to.

Thanks!

Upvotes: 2

Views: 1673

Answers (3)

neevek
neevek

Reputation: 12128

A pointer must point to something(including garbage) or nothing(means the pointer being initialized to NULL). A pointer is an indirect reference to an object. If you don't have such an object for your pointer to point to, you may not need a pointer. You can simply call setArgument:NULL atIndex:2.

The case to use a pointer like that in your code is to pass an output parameter, whose value will be set in the function you call, and in this case, you probably don't need to initialize the parameter before passing it to the function, the function is supposed to take care of assigning correct value to it.

So in your case, if you didn't mean to use a output parameter, you only need to pass the primitive BOOL to the function, no pointer needed.

EDIT

I just took a look at the doc for NSInvocation. The answer is the same as others', NO.

You have to pass a pointer, which must point to an existing object for NSInvocation to work correctly.

Upvotes: 0

Stefan Bossbaly
Stefan Bossbaly

Reputation: 6794

The answer is no. A pointer must point to an address in memory. So first you must allocate that memory and then send the address of that allocated memory into the method. In the case of a primitive the memory allocated will be on the stack and with an object the memory allocated for the object will be on the heap and the address of that object will be stored on the stack. As for the error you are getting the void* parameter of setArgument:atIndex: seems to want an object and not a primivtive. Have you tried using a NSNumber to represent a bool. NSNumber comes with a numberWithBool: method.

Upvotes: 0

cobbal
cobbal

Reputation: 70703

No, not in any clean, reliable way.

NSInvocation will dereference whatever pointer you send it and copy data of length specified by the method signature out of it. You need to have that information somewhere so you can get an address to it, and having the local variable as you have is the best way to do so.

Upvotes: 6

Related Questions