Blocks能够访问局部变量,可是不能修改,闭包
声明block的时候其实是把当时的临时变量又复制了一份,spa
在block里即便修改了这些复制的变量,也不影响外面的原始变量。即所谓的闭包。指针
若是修改局部变量,须要加__block。code
API Reference对__block变量修饰符有以下几处解释对象
//A powerful feature of blocks is that they can modify variables in the same lexical scope. You signal that a block can modify a variable using the __block storage type modifier. //At function level are __block variables. These are mutable within the block (and the enclosing scope) and are preserved if any referencing block is copied to the heap.
大概意思归结出来就是两点:
1.__block对象在block中是能够被修改、从新赋值的。
2.__block对象在block中不会被block强引用一次,从而不会出现循环引用问题。blog
__weak __typeof(&*self)weakSelf =self; 等同于内存
__weak UIViewController *weakSelf =self;ci
为何不用__block 是由于经过引用来访问self的实例变量 ,self被retain,block也是一个强引用,文档
引发循环引用,用__week是弱引用,当self释放时,weakSelf已经等于nil。it
API Reference对__weak变量修饰符有以下几处解释:
__weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
使用了__weak修饰符的对象,做用等同于定义为weak的property。天然不会致使循环引用问题,由于苹果文档已经说的很清楚,当原对象没有任何强引用的时候,弱引用指针也会被设置为nil。
所以,__block和__weak修饰符的区别实际上是挺明显的:
1.__block无论是ARC仍是MRC模式下均可以使用,能够修饰对象,还能够修饰基本数据类型。
2.__weak只能在ARC模式下使用,也只能修饰对象(NSString等),不能修饰基本数据类型(int)。
3.__block对象能够在block中被从新赋值,__weak不能够。
PS:__unsafe_unretained修饰符能够被视为iOS SDK 4.3之前版本的__weak的替代品,不过不会被自动置空为nil。因此尽量不要使用这个修饰符。
总之,_block & _weak:
在block代码块中也会用相似代码来修饰变量,
__block 为了改变block代码块外部的变量。例如:你在外面定义了一个整形变量,想要在block块内改变他,那么,就要用__block 来修饰这个整形变量。
__weak 是为了防止循环引用,引发内存泄露的问题。 例如: __weak ViewController *wself = self;