Block

1、Why "copy":

@property (nonatomic, copy) void (^actionBlock)(void);

The syntax may still be a bit scary, but recall that a block looks a lot like a function.

shows the various components of a block.

Notice that the property is declared as copy. This is very important. Blocks behave a bit differently than the rest of the objects you have been working with so far. When a block is created, it is created on the stack, as opposed to being created on the heap like other objects. This means that when the method that a block is declared in is returned, any blocks that are created will be destroyed along with all of the other local variables. In order for a block to persist beyond the lifetime of the method it is declared in, a block must be sent the copy message. By doing so, the block will be copied to the heap – thus you declare the property to have the copy attribute.

2.block循环引用在MRC中的解决方案:

在《Effective Objective-C 2.0》这本书的最后一章讲了关于NSTimer会引起循环引用的问题,这个问题在block中是普遍存在的,但是,当时的案例是运行在ARC环境下的,如果是MRC环境,则需要略作改动,如下是MRC环境下的例子。

例子:

__block typeof(self) weakSelf = self;

_config.stateBlock = ^(NSString *state) {

[weakSelf retain];

[weakSelf handleState:state];

[weakSelf release];

};

你可能感兴趣的:(Block)