iosautomatic-ref-countingnsinvocationmessage-forwarding

Get block argument from NSInvocation with ARC


I'm trying to get the block argument from the NSInvocation in NSProxy's forwardInvocation: Is this the correct syntax? Would it leak memory?

typedef void(^SuccessBlock)(id object);
void *successBlockPointer;
[invocation getArgument:&successBlockPointer atIndex:index];
SuccessBlock successBlock = (__bridge SuccessBlock)successBlockPointer;

Or should I use?

typedef void(^SuccessBlock)(id object);
SuccessBlock successBlock;
[invocation getArgument:&successBlock atIndex:index];

What about other argument types like objects?

__unsafe_unretained id myObject = nil; // I don't think this could be __weak? Is that correct?
[invocation getArgument:&myObject atIndex:index];

Do I have to do anything else to correctly free up allocated memory?

Thanks in advance.


Solution

  • Yes. Under ARC, it is incorrect to use

    id myObject = nil; // or any object type or block type
    [invocation getArgument:&myObject atIndex:index];
    

    because &myObject is type id __strong *, i.e. pointer to strong reference. Whoever assigns to the strong reference pointed to by this pointer must take care to release the previous value and retain the new value. However, getArgument:atIndex: does not do that.

    You are right. The two correct ways to do it you have already found: 1) do it with void * and then assign it back into object pointer, or 2) do it with __unsafe_unretained object pointer.