本文介绍了Objective-C块语法-有人可以解释吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释该块语法如何工作吗?

Can anyone explain how this block syntax works?

AStreamBuilder stream_builder = [ [ ^( void )
   {
      // some more code..
      return (NSInputStream *)[ NSInputStream inputStreamWithFileAtPath: some_path ];
   } copy ] autorelease ];
   return stream_builder;

这里的街区名称是什么?为什么要复制该块然后将其自动释放?我对这里发生的事情感到困惑.据说该块返回AStreamBuilder,但是在该块的主体内部它返回一个NSInputStream实例.

What's the name of the block here? Why is the block being copied and then autoreleased? I'm sort of confused with what's going on here.. the block is said to return AStreamBuilder but inside the body of the block it returns an instance of NSInputStream.

任何人都可以分解吗?

推荐答案

这是代码段:

^( void )
   {
      // some more code..
      return (NSInputStream *)[ NSInputStream inputStreamWithFileAtPath: some_path ];
   }

它不接收任何参数(因此为(void)),并返回NSInputStream的实例.请注意,它没有一个名称",例如:

it doesn’t receive any parameter (hence (void)) and it returns an instance of NSInputStream. Note that it doesn’t have a ‘name’ — in the same sense that, for example:

[[NSNumber alloc] initWithInt:42];

也没有名称".

由于在堆栈上创建了块,因此如果需要返回一个块,则必须将其从堆栈复制到堆中(因此-copy).这是一个拥有的对象;为了返回调用者不拥有的对象,该块会自动释放(因此-autorelease):

Since blocks are created on the stack, if you need to return a block then you must copy it from the stack to the heap (hence -copy). This is an owned object; in order to return an object that’s not owned by the caller, the block is autoreleased (hence -autorelease):

[ [ ^( void )
   {
      // some more code..
      return (NSInputStream *)[ NSInputStream inputStreamWithFileAtPath: some_path ];
   } copy ] autorelease ];

因此,上面的摘录是一个自动释放的块,该块已从堆栈复制到堆中.它已分配给变量

So the excerpt above is an autoreleased block that was copied from the stack to the heap. It is assigned to a variable

AStreamBuilder stream_builder = …

,对于没有任何参数并且返回类型为NSInputStream(或与之兼容的类型)的块,AStreamBuilder可能是typedef.请注意,AStreamBuilder是块类型,而不是该块返回的值的类型.像这样:

so it’s likely that AStreamBuilder is a typedef for a block that receives no parameters and has return type NSInputStream (or a type compatible with that). Note that AStreamBuilder is a block type as opposed to the type of the value returned by the block. Something like:

typedef NSInputStream * (^AStreamBuilder)(void);

这篇关于Objective-C块语法-有人可以解释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:48