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:
Then you simply assigned it to a property with
assign:When the containing method returns, the
blockvariable will go out of scope and deallocated. So, with this in mind, you mustcopythe block object and then store it in your instance variable. That way, you can own the block for the lifetime of the containing object.