Defining Objective-C blocks as properties - best practice

前端 未结 3 842
面向向阳花
面向向阳花 2020-12-13 10:56

I\'ve recently come across an Apple document that shows the following property declaration for a block:

@interface XYZObject : NSObject
@property (copy) void         


        
3条回答
  •  我在风中等你
    2020-12-13 11:32

    Blocks are, by default, allocated on the stack. This is an optimization, since stack allocation is much cheaper than heap allocation. Stack allocation means that, by default again, a block will cease to exist when the scope in which it is declared exits. So a block property with retain semantics will result in a dangling pointer to a block that doesn't exist anymore.

    To move a block from the stack to the heap (and thus give it normal Objective-C memory management semantics and an extended lifetime), you must copy the block via [theBlock copy], Block_copy(theBlock), etc. Once on the heap, the block's lifetime can be managed as needed by retaining/releasing it. (Yes, this applies in ARC too, you just don't have to call -retain/-release yourself.)

    So you want to declare block properties with copy semantics so the block is copied when the property is set, avoiding a dangling pointer to a stack-based block.

提交回复
热议问题