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 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:
it doesn’t receive any parameter (hence
(void)) and it returns an instance ofNSInputStream. Note that it doesn’t have a ‘name’ — in the same sense that, for example: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):So the excerpt above is an autoreleased block that was copied from the stack to the heap. It is assigned to a variable
so it’s likely that
AStreamBuilderis atypedeffor a block that receives no parameters and has return typeNSInputStream(or a type compatible with that). Note thatAStreamBuilderis a block type as opposed to the type of the value returned by the block. Something like: