Block

作者: walter0817 | 来源:发表于2016-03-11 19:45 被阅读18次

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];

};

相关文章

  • iOS开发之Block原理探究

    Block概述 Block本质 Block调用 Block分类 Block循环引用 Block原理探究 Block...

  • block的使用

    定义block 返回类型 (^block名称)(参数) = ^(){block内容}; 调用block block...

  • Block 02 - __block

    Block 02 - __block __block 的作用 __block 可以解决 Block 内部无法修改 ...

  • iOS面试之Block大全

    Block Block内容如下: 关于Block 截获变量 __block修饰符 Block的内存管理 Block...

  • iOS面试之Block模块

    Block Block内容如下: 关于Block 截获变量 __block修饰符 Block的内存管理 Block...

  • iOS Block

    Block的分类 Block有三种类型:全局Block,堆区Block,栈区Block 全局Block 当Bloc...

  • iOS block 为什么官方文档建议用 copy 修饰

    一、block 的三种类型block 三种类型:全局 block,堆 block、栈 block。全局 block...

  • iOS开发block是用copy修饰还是strong

    Block分为全局Block、堆Block和栈Block1、在定义block没有引用外部变量的时候,block为全...

  • block 初探

    全局block, 栈block, 堆block

  • Block

    一、Block本质 二、 BlocK截获变量 三、__block 修饰变量 四、Block内存管理 五、Block...

网友评论

      本文标题:Block

      本文链接:https://www.haomeiwen.com/subject/cucxlttx.html