Are blocks passed by reference or by value from one call on stack to another?

ios, iphone, objective-c, objective-c-blocks

Solution

Blocks are pointer types and the pointer is passed-by-value.

So a block created on the stack and passed to a function/method is not copied into the call frame of the callee.

However that does not mean the block may not be copied to the heap under some circumstances you may not expect when using ARC. Stack blocks are really an (internal) optimisation which due to the way they were introduced were surfaced to the user. You should not rely on blocks being on the stack.

BTW: "Copying a block" is usually just used to refer to whether the block is copied from the stack to the heap, which is not what you are asking, so you might get answers along that line.

Problem

When I pass block to other method (not to heap with `Block_copy` or `@property(copy)`), is it copied or is it passed by reference? I mean: ``` - (void)processBlock:(MyBlockType)block param:(int)param { } - (void)someMethod { int b1 = 10; int a1 = 9; [self processBlock:^int(int number, id object) { NSLog(@"block"); return 1 + a1; } param:b1]; } ``` It is `NSStackBlock` - because it captures "a" variable, so it is allocated on stack. When I pass them to the other method is it copied and stored on `processBlock's` section of stack, or just passed by reference? like that: ``` copyOf myBlock copyOf b1 processBlock .......... ..other variables.. a1 b1 myBlock someMethod .......... ``` Or Like that: ``` *myBlock (jast a pointer) copyOf b1 processBlock .......... ..other variables.. a1 b1 myBlock someMethod .......... ```

Original source

Related problems