I'm getting into the use of blocks in Objective-C and haven't really found a good explanation of why a block, if you're going to assign it to an instance variable, has to be assigned with copy
and not assign
?
for example:
typedef void (^MyBlock)();
@interface SomeClass : NSObject
{
MyBlock myblock;
// Other ivars
}
@property (nonatomic, copy) MyBlock myblock; // Why must this be 'copy'???
// other declarations
@end
Well, let's analyze this:
Let's say you create a block inside of some method, assign it to some variable:
MyBlock block = ^{};
Then you simply assigned it to a property with assign
:
self.myblock = block;
When the containing method returns, the block
variable will go out of scope and deallocated. So, with this in mind, you must copy
the block object and then store it in your instance variable. That way, you can own the block for the lifetime of the containing object.
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