开发者

Objective-C block syntax - can someone explain this?

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;

What's the name开发者_StackOverflow社区 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.

Can anyone break this down?


This is the block:

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

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];

doesn’t have a ‘name’, either.

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 = …

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);


What's the name of the block here?

The new block is assigned to the variable stream_builder. It doesn't have a name per se since a block is an "anonymous inline collection of code"

Why is the block being copied and then autoreleased?

Because it's going to be kept around after the current scope (it is being returned from the method/function). It therefore needs to be copied to the heap.

the block is said to return AStreamBuilder but inside the body of the block it returns an instance of NSInputStream

The function/method you're in (the one that ends with return stream_builder;) returns an AStreamBuilder (= the newly created block). The block itself will return an NSStream when invoked at some point in the future.


The block is being copied to move it from the stack to the heap. This is required if you want to use the block outside of the scope where you create it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜