Reputation: 1129
Should I copy the block passed to [c2 fun2:]
based on the following class structure please?
@implementation Class1 {
Class2 *c2;
id var1;
}
- (void) fun1 {
[c2 fun2:^{
[var1 someFun];
}];
}
@end
@implementation Class2
- (void) fun2:(void(^)(void))block {
[self someFun1];
block();
}
@end
Upvotes: 1
Views: 1084
Reputation: 2883
First of all you do not need to copy blocks manually under ARC (they are moved from stack to heap automatically if needed).
In your case you do not need to copy it since your block is called before fun1
ends snd it stack drains.
Upvotes: 1
Reputation: 38181
No you don't have to make a copy in this case. Why?
Since you do not store this block for later usage! You are just using this block immediately in invoked function, so you have a warranty that all references variables used int this block will be still valid.
You have to make a copy, if you are storing block for later usage!
I would say that it is even better to not create copy of block if it is possible. Blocks are created on stack not on heap, so creation of block is very fast operation. When you are creating a copy of block copy is created on heap (this is more expensive) and all strong references used in block have to be retained (another potentially costly operation) and some variables have to be copied (this is usually fast, except for some complex objects).
Upvotes: 0
Reputation: 17053
If you store a block to run it later (usually in some property) then you have to copy it because blocks in Objective C are created in stack. With properties it is a common approach to declare it with copy
:
@property(copy) block_declaration block_name;
If you do not store a block for a later use and call it immediately (like in your case) - you do not have to copy it.
Upvotes: 2