Why should the objc block assignment be “copy” rather than “assign”?

I use blocks in Objective-C and have not really found a good explanation why a block, if you are going to assign it to an instance variable, should be assigned copy rather than assign ?

eg:

 typedef void (^MyBlock)(); @interface SomeClass : NSObject { MyBlock myblock; // Other ivars } @property (nonatomic, copy) MyBlock myblock; // Why must this be 'copy'??? // other declarations @end 
+4
source share
3 answers

Ok, let it analyze this:

Let's say you create a block inside some method, assign it to some variable:

 MyBlock block = ^{}; 

Then you just assigned it to the property with assign :

 self.myblock = block; 

When the return method returns, the variable block will go out of scope and become free. Therefore, keeping this in mind, you must copy lock the object, and then save it in the instance variable. This way you can own a block for the lifetime of the containing object.

+9
source

This is because the blocks are weird .

+4
source

There is a good explanation in the wwdc video "Advanced Objective-C and Garbage Collection", which is worth a look if you start entering blocks and want some of the internal ones to be explained. There are other good conversations. Highly recommended.

0
source

Source: https://habr.com/ru/post/1335184/


All Articles