开发者

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 de开发者_高级运维clarations

@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.


It's because blocks are weird.


there is a good explanation in the wwdc video "Advanced Objective-C and Garbage Collection" worth watching if you are starting to get into blocks and want some of the internals explained. There are some other great talks as well in there. Highly recommended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜