Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the assignment of an objc block have to be 'copy', not 'assign'?

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
like image 788
Wayne Hartman Avatar asked Dec 13 '22 16:12

Wayne Hartman


1 Answers

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.

like image 153
Jacob Relkin Avatar answered Jan 31 '23 10:01

Jacob Relkin