双指针作为Objective

双指针作为Objective

本文介绍了双指针作为Objective-C块参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能(并且如果是安全的话)创建/使用以双指针作为参数的块?

Is it possible (and if so, safe) to create/use a block which takes a double pointer as an argument?

例如:

- (void)methodWithBlock:(void (^)(NSError **error))block;

其他背景,研究和问题:

Additional context, research, and questions:

  • 我正在使用ARC.
  • 当我声明上面的方法并尝试调用它时,XCode会自动完成我的方法调用,如下所示:[self methodWithBlock:^(NSError *__autoreleasing *error) {}];__autoreleasing在这里是什么意思,为什么要添加?我认为这与ARC有关.
  • 如果这种 是可能且安全的,那么指针是否仍可以像在其他任何地方一样在块中被取消引用?
  • 通常,执行我正在描述的内容和简单地将双指针作为方法参数(例如- (void)methodWithDoublePointer:(NSError **)error;)传递之间有什么重要区别?应该考虑什么特殊的考虑因素(再次假设完全有可能)?
  • I'm using ARC.
  • When I declare the method above and attempt to call it, XCode autocompletes my method invocation as follows: [self methodWithBlock:^(NSError *__autoreleasing *error) {}];What does __autoreleasing mean here and why is it being added? I presume it has something to do with ARC.
  • If this is possible and safe, can the pointer still be dereferenced in the block as it would be anywhere else?
  • In general, what are the important differences between doing what I'm describing, and simply passing a double pointer as a method parameter (e.g. - (void)methodWithDoublePointer:(NSError **)error;)? What special considerations, if any, should be taken into account (again assuming this is possible at all)?

推荐答案

答案都是是".不...

The answers are both Yes & No...

在基本级别上,将指针传递给块的指针与将指针传递给方法没有什么不同;并且,通常的条件是您的指针必须有效,完全可以.

At a base level passing pointers to pointers to blocks is no different than passing them to methods; and, with the usual proviso that your pointers must be valid, is perfectly OK.

然而 __autoreleasing在这里非常很重要,并且与ARC和 pass-by-writeback 捆绑在一起.使用该块是否会按预期工作将取决于上下文,因为编译器在传递NSError * __autoreleasing *类型的参数作为传递回写实现的一部分时经常使用隐藏变量.

However that __autoreleasing is very significant here and is tied up with ARC and pass-by-writeback. Whether using the block will work as expected will be dependent on context as the compiler often uses hidden variables when passing parameters of type NSError * __autoreleasing * as part of the pass-by-writeback implementation.

如果不需要传递写回或不合适,则您可能希望声明您采用其他类型的块,例如NSError * __strong *.阅读此答案,其中解释了在以下情况下会发生什么引擎盖,应该可以帮助您确定在您的上下文中块声明是否正确.

If pass-by-writeback is not what you need, or is unsuitable, you may wish to declare you block as taking a different type, such as NSError * __strong *. Read this answer which explains what happens under the hood, that should help you decide whether in your context the block declaration is good.

总而言之(a)声明该块是可以的,但(b)您需要了解如何调用它以及可能需要更改签名.

In summary (a) declaring the block is fine, but (b) you need to understand how it may be called and may need to change the signature.

这篇关于双指针作为Objective-C块参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:54