简体   繁体   English

使用ARC从NSInvocation获取块参数

[英]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? 我试图从NSProxy的forwardInvocation中的NSInvocation获取块参数:这是正确的语法吗? 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 在ARC下,使用不正确

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. 因为&myObject是类型id __strong * ,即指向强引用的指针。 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. 但是, getArgument:atIndex:不会这样做。

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. 你已经找到了两种正确的方法:1)用void *做它,然后将它分配回对象指针,或2)用__unsafe_unretained对象指针做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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