Block的使用和循环引用的隐患

Block本身会产生Retain么

Block其实就是一段代码段,假设我在ClassA中使用ClassB的Block,block实际存在于ClassA的内存段p:0xXXXXX.也就是说在运行的时候如果ClassB的Block被使用,他会等待Block的代码段出现,如下.

typedef void(^CompletionBlock)(NSString *message);
//ClassB.h
- (void)classBFunction:(CompletionBlock)completion;
//ClassB.m
- (void)classBFunction:(CompletionBlock)completion {
completion(@"wait Block");
}

此时,我在ClassA中声明ClassB,并且调用该函数

//ClassA.m
ClassB *b = [[ClassB alloc]init];
[b classBFunction:^(NSString *message) {
    NSLog(@"%@",message);
    }];

此时NSLog(@"%@",message)其实是ClassA中的代码片段,处于地址p.也就是说如果ClassB想在classBFunction:内部completion执行传递来的NSLog,那么ClassA的内存千万不能被释放.也就是说ClassB必须用Block对ClassA产生一个Retain,一个强引用.

Block分几种

Block一共分三种

  1. NSGlobalBlock:没有使用除了Block参数以外的变量;
  2. NSStackBlock:使用了Block参数以外的变量,位于栈内存,函数返回后Block就被释放;
  3. NSMallocBlock:位于堆内存,使用引用计数。

示例

BlkSum blk1 = ^ long (int a, int b) {
  return a + b;
};
NSLog(@"blk1 = %@", blk1);// blk1 = <__NSGlobalBlock__: 0x47d0>

int base = 100;
BlkSum blk2 = ^ long (int a, int b) {
  return base + a + b;
};
NSLog(@"blk2 = %@", blk2); // blk2 = <__NSStackBlock__: 0xbfffddf8>

BlkSum blk3 = [[blk2 copy] autorelease];
NSLog(@"blk3 = %@", blk3); // blk3 = <__NSMallocBlock__: 0x902fda0>

Block如何产生的循环引用

在较早版本的Xcode,由于Block会对.m本身的ClassA产生一个Retain,而ClassA如果想调用ClassB的Block,自然也会对ClassB产生一个Retain.所以Block作为传送指针的通道,就让AB互相强引用了,例如Bang的文献里说的.

@interface ClassAViewController ()
@property (nonatomic, strong) ClassB *classB;
@end

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _classB = [[ClassB alloc]init];
    [_classB blockFunction:^(UIView *view) {
        [self completionBlock];
    }];
}

- (void)completionBlock {
    NSLog(@"ClassAViewController Comlpetion Block");
}

- (void)dealloc {
    NSLog(@"ClassAViewController did dealloc");
}

由于testFunction的block要调用ClassA(self)里的函数,为了防止这一段函数被释放,必须对ClassA产生一个Retain.在以前的版本为了避免产生循环引用,会使用一个weak指针指向self,然后通过weak指针调用self的函数.

_b = [[ClassB alloc]init];
id weakself = self;
[_b testFunction:^(UIView *view) {
    [weakself completionBlock];
}];

经过Xcode7.2实际测试,这样书写已经不会产生循环引用,dealloc会被正常调用

还有一种可能的情况,有3个类形成通过block循环引用,但是很少见.

+-----------+           +-----------+           +-----------+
|   self    |           |    obj    |           |   Block   |
|  ClassA   | --------> |   ClassC  | --------> |  ClassB   |
| retain 1  |           |  retain 1 |           | retain 1  |
|           |           |           |           |           |
+-----------+           +-----------+           +-----------+
     ^                                                |
     |                    strong                      |
     +------------------------------------------------+

我去专门复现也无法复现出来,因为ClassC中调用ClassB的Block,访问的是ClassC的内存段,ClassB基本很少有手段对ClassA产生Retain.因为总需要一个指针把ClassA传递给ClassB,如果使用弱指针传递,就相当旧版本时的weakself了

+-----------+           +-----------+           +-----------+
|   self    |           |    obj    |           |   Block   |
|  ClassA   | --------> |   ClassC  | --------> |  ClassB   |
| retain 1  |           |  retain 1 |           | retain 1  |
|           |           |           |           |           |
+-----------+           +-----------+           +-----------+
                            ^                           |
                            |            weak           |
                            +---------------------------+

那是不是ARC下Block不会产生循环引用了

不是,与其担心Block造成循环引用,更应该关心透穿时使用什么指针

+-----------+           +-----------+           +-----------+
|   self    |   strong  |    obj    |   strong  |   Block   |
|  ClassA   | --------> |   ClassC  | --------> |  ClassB   |
| retain 1  |  ?pointA  |  retain 1 |   pointA  | retain 1  |
|           | <---------|           | --------> |           |
+-----------+           +-----------+           +-----------+
                            ^                           |
                            |            weak           |
                            +---------------------------+

循环引用例子

  1. 主ViewController用来Present出ClassAVC
  2. ClassAVC中有两个按钮,一个是dismiss自己,一个是present出ClassCVC
  3. ClassC中声明pointA,用于把ClassA传递给ClassC
  4. 在ClassC中初始化ClassB,执行闭包,传入pointA指针.

在上述过程中,pointA应该使用weak,如果使用了strong,ClassA对ClassC本身就是强引用,如果pointA也是强引用,就形成了循环引用,这种前后两个界面互相传递的情况比较常见,一不小心就会形成循环引用,这也是为什么推荐使用代码洁癖weak的prorerty的原因.

+-----------+                   +-----------+   
|   self    |   strong          |    obj    | 
|  ClassA   | --------------->  |   ClassC  |
| retain 1  |   strong-pointA   |  retain 1 |
|           | <---------------- |           | 
+-----------+                   +-----------+          

ClassA

//ClassA.h
@interface ClassAViewController : UIViewController
- (void)completionBlock;
@end
//ClassA.m
#import "ClassCViewController.h"

@interface ClassAViewController ()
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) ClassCViewController *classCVC;
@property (nonatomic, strong) UIButton *dismissBtn;
@end

@implementation ClassAViewController

- (void)touchUpInsideButton:(UIButton *)button {
    _classCVC = [[ClassCViewController alloc]init];
    _classCVC.classAVC = self;
    [self presentViewController:_classCVC animated:YES completion:nil];
}

- (void)touchUpInsideDismissBtn:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)completionBlock {
    NSLog(@"ClassAViewController Comlpetion Block");
}   

- (void)dealloc {
    NSLog(@"ClassAViewController did dealloc%p",self);
}
@end

ClassC

//ClassC.h
@interface ClassCViewController : UIViewController
//此处是pointA,使用了Strong,形成循环引用
@property (nonatomic, strong)  ClassAViewController *classAVC;
@end
//ClassC.m
#import "ClassB.h"
#import "ClassAViewController.h"

@interface ClassCViewController ()
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) ClassB *classB;
@end

@implementation ClassAViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _classB = [[ClassB alloc]init];
    [_classB blockFunction:^(UIView *view) {
        [_classAVC completionBlock];
    }];
}

- (void)touchUpInsideButton:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    NSLog(@"ClassCViewController did dealloc%p",self);
}
@end

ClassB

//ClassB.h
@interface ClassB : NSObject
- (void)blockFunction:(void(^)(UIView *view))completion;
@end
//ClassB.m
- (void)blockFunction:(void(^)(UIView *view))completion {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    [view setBackgroundColor:[UIColor redColor]];
    completion(view);
}

变量进入Block是传值还是传址

使用了局部变量的NSStackBlock,对局部变量采用的是传值形式的调用,进入Block后更改不会影响原变量.如果想进行传址,需要加上__block标注

__block int base = 100;
BlkSum blk2 = ^ long (int a, int b) {
    base += 10;
    return base + a + b;
};
NSLog(@"blk2 = %@", blk2); // blk2 = <__NSStackBlock__: 0xbfffddf8>

参考文献

[1] http://git.devzeng.com/blog/ios-arc-block-retain-cycle.html
[2] http://tanqisen.github.io/blog/2013/04/19/gcd-block-cycle-retain/
[3] http://git.devzeng.com/blog/ios-arc-block-retain-cycle.html

你可能感兴趣的:(Block的使用和循环引用的隐患)