07
Apr
10

NSInvocation+CWVariableArguments

Here’s a neat trick: parsing a variable argument list into an NSInvocation call in order to call an arbitrarily argumented method on the main UI thread.

… Too bad that they are untyped? 
No despair, we know the target object for our invocation, and we know what method to call. So we have what we need to fetch the NSMethodSignature object for the call, that contains all the type information we need to safely process the va_list.

Our target machine is a Mac running 32- or 64-bit Intel CPU, or an iPhone OS device with a 32 bit ARM CPU. Turns out that on both platforms va_list is simply a void* pointer, to the stack frame. Even better va_start() will always flush any argument passed into the register on the stack frame. So we can skip most of the boring argument handling, by treating the arguments like a byte buffer, only advancing and aligning the buffer according to the information in the NSMethodSignature object…

Not too sure that we’d actually recommend this as being a particularly good practice as compared to the conventional process of packing up your arguments in an NSDictionary, but it’s rather interesting code to look through and see just how the variable arguments are reconciled with the NSMethodSignature. Just in case you ever have a good reason to know how!

h/t: LinkedIn’s CocoaTouch!


Leave a Reply