简体   繁体   中英

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.

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 * , ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM