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
..........
First, let's clear up some terminology, because that's at the root of the confusion.
If we get really technical, you cannot "pass a block" -- You can never deal with "a block". You can only manipulate "pointers to blocks". The type something (^)()
is a pointer-to-block type. A block literal is an expression of pointer-to-block type. The functions Block_copy
and Block_release
take pointer-to-block type. In short, everything you do with blocks must be done with pointers to blocks.
In Objective-C, blocks are objects. You will recognize the analogous concept in Objective-C that you can never deal with "an object" directly. You can only deal with pointers to objects.
With that cleared up, everything in Objective-C, like in C, is passed and assigned by value. There is no "pass by reference".
In the code you show, you are passing a pointer to a block, by value. That pointer points to a block object, which, yes, resides on the stack frame. If someone calls copy on this pointer (and it is not certain from your code that this occurs, but assuming that it does), then the copy function will return another pointer to a new block object, which is in the heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With