How do I (or can I even) pass a nil argument to an NSInvocation object?
I tried to do this:
NSMethodSignature* signature = [AClass instanceMethodSignatureForSelector:@selector(aMethod:theOtherArg:)];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: signature];
[invocation setTarget: aTargetObj];
[invocation setSelector: @selector(aMethod:theOtherArg:)];
/* I've tried both this way */
AnObj* arg1 = nil;
AnotherObj* arg2 = nil;
[invocation setArgument: &arg1 atIndex:2];
[invocation setArgument: &arg2 atIndex:3];
/* and this way */
//[invocation setArgument: nil atIndex:2];
//[invocation setArgument: nil atIndex:3];
NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithInvocation:invocation];
//opQueue is an NSOperationQueue object
[opQueue addOperation:operation];
The first approach will crash with this message:
Thread 0 Crashed:
0 libSystem.B.dylib 0x927c1f10 strlen + 16
1 com.apple.CoreFoundation 0x92dd1654 __NSI3 + 500
2 com.apple.CoreFoundation 0x92dd1994 -[NSInvocation retainArguments] + 132
3 com.apple.Foundation 0x96a50c5e -[NSInvocationOperation initWithInvocation:] + 78
The second approach will crash with this message:
Error: Exiting due to caught object *** -[NSInvocation setArgument:atIndex:]: NULL address argument
Thanks in advance for any help!
Yes, you can pass nil arguments. More precisely, you can pass a valid pointer whose contents are nil.
I haven’t been able to reproduce your particular problem. Here’s the code I’ve used to test it. There’s probably something else in your program that’s causing the error.
I’ve also tested it without using NSInvocationOperation and sending -retainArguments directly, since that’s what seems to be triggering your error.
For the record, your second approach won’t work since -[NSInvocation setArgument:atIndex:] expects a valid memory address pointing to a buffer which will be copied. In the case of object arguments, the buffer must contain the address of the object. The address of the object can be zero but the address of the buffer must be valid.