关于iOS block循环引用的一点理解

When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:

  1. If you access an instance variable by reference, a strong reference is made to self;
  2. If you access an instance variable by value, a strong reference is made to the variable.

主要有两条规则:
第一条规则,如果在block中访问了属性,那么block就会retain住self。
第二条规则,如果在block中访问了一个局部变量,那么block就会对该变量有一个强引用,即retain该局部变量。

这是官方文档里面提到的,

 

根据这两条规则,我们可以知道发生循环引用的情况:

1
2
3
4
5
6
7
8
9
10
11
//规则1
self.myblock = ^{
[self doSomething]; // 访问成员方法
NSLog(@"%@", weakSelf.str); // 访问属性
};

//规则2
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSString* string = [request responseString];
}];

 

官网提供了几种方案,我们看看第一种,用__block变量:

在MRC中,__block id x不会retain住x;但是在ARC中,默认是retain住x的,我们需要
使用__unsafe_unretained __block id x来达到弱引用的效果。

那么解决方案就如下所示:

1
2
3
4
5
6
__block id weakSelf = self;  //MRC
//__unsafe_unretained __block id weakSelf = self; ARC下面用这个
self.myblock = ^{
[weakSelf doSomething];
NSLog(@"%@", weakSelf.str);
};
posted @ 2015-07-23 10:51  橙子哥哥  阅读(1623)  评论(0编辑  收藏  举报