iOS-Block 中 为何使用 weakSelf 和 strongSelf

目录

本篇幅代码会有些多,需要读者耐心看完。

一 block 循环引用讲解

详细请移步至 iOS-底层原理(11)-block-循环引用详解,该文章详细讲解了有关 block 引用的原理及解决思路。

原理就是相互引用

iOS-Block 中 为何使用 weakSelf 和 strongSelf_第1张图片
image.png
二 为何使用 weakSelf 可以解决循环引用
  • __weak:不会产生强引用,指向的对象销毁时,会自动让指针置为nil
  • __unsafe_unretained:不会产生强引用,不安全,指向的对象销毁时,指针存储的地址值不变
iOS-Block 中 为何使用 weakSelf 和 strongSelf_第2张图片
image.png

代码佐证 - 在 MRC 环境下

  • 1 直接在 block里面使用 self
- (void)test1 {
    // 引用计数
    NSLog(@"self1 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
    
    // 循环引用
    self.myBlock = ^{
        [self test];
    };
    self.myBlock();
}

- (void)test {
    NSLog(@"test 方法 self 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesBegan self = %lu",(unsigned long)[self retainCount]);
}
  • 运行结果
2019-06-09 14:44:32.975002+0800 WeakStrongSelfDemo[6897:172037] self1 内存地址:0x7fc69ef14cc0 引用计数:9
2019-06-09 14:44:32.975150+0800 WeakStrongSelfDemo[6897:172037] test方法 self 内存地址:0x7fc69ef14cc0 引用计数:10
2019-06-09 14:44:34.638030+0800 WeakStrongSelfDemo[6897:172037] touchesBegan self 内存地址:0x7fc69ef14cc0 引用计数:5

总结:直接在 block 中使用 self,发现其引用计数+1,执行完touchesBegan方法后,引用计数变成5.

  • 2 在 block 中使用 weakSelf
typedef void(^MyBlock)(void);

@interface TestViewController ()
/** myBlock */
@property(nonatomic, copy)MyBlock myBlock;
@end

- (void)test2 {
    // 引用计数
    NSLog(@"self1 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
    
    __weak typeof(self) weakSelf = self;
    NSLog(@"weakSelf 内存地址:%p 引用计数:%lu",weakSelf,(unsigned long)[weakSelf retainCount]);
    
    NSLog(@"self2 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
    
    // 循环引用
    self.myBlock = ^{
        [weakSelf test];
    };
    self.myBlock();
}
  • 运行结果
2019-06-09 14:49:46.690693+0800 WeakStrongSelfDemo[6952:174797] self1 内存地址:0x7ffd7dc1e520 引用计数:9
2019-06-09 14:49:46.690852+0800 WeakStrongSelfDemo[6952:174797] weakSelf 内存地址:0x7ffd7dc1e520 引用计数:11
2019-06-09 14:49:46.690931+0800 WeakStrongSelfDemo[6952:174797] self2 内存地址:0x7ffd7dc1e520 引用计数:11
2019-06-09 14:49:46.691016+0800 WeakStrongSelfDemo[6952:174797] test方法 self 内存地址:0x7ffd7dc1e520 引用计数:12
2019-06-09 14:49:49.165380+0800 WeakStrongSelfDemo[6952:174797] touchesBegan self 内存地址:0x7ffd7dc1e520 引用计数:4

总结:selfweakSelf的内存地址相同,在没有执行 block之前,他两的引用计数值相同。执行完 block 后,执行touchesBegan屏幕点击,发现引用计数变为4。注意前面直接使用self的时候,引用计数是5。即得出结论

  1. 直接在block中使用self,会造成循环引用, block 执行完后,self的引用计数不正常(应该为4的,但实际上是 5,多 1是因为被block引用着)
  2. 如果使用weakSelf不会造成循环引用,self的引用计数正常(至于为啥是 4,应该是系统其它变量引用着 self)。
三 为何使用 strongSelf

在 doSomething 中,weakSelf 不会变成 nil,不过在 doSomething 执行完成,调用第二个方法 doOtherThing 的时候,weakSelf 有可能被释放,于是,strongSelf 就派上用场了:

__weak __typeof__(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    __strong __typeof(self) strongSelf = weakSelf;
    [strongSelf doSomething];
    [strongSelf doOtherThing];
});
  • 代码例子佐证
- (void)test3 {
    // 引用计数
    NSLog(@"self1 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
    
    __weak typeof(self) weakSelf = self;
    NSLog(@"weakSelf 内存地址:%p 引用计数:%lu",weakSelf,(unsigned long)[weakSelf retainCount]);
    
    NSLog(@"self2 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
    
    NSLog(@"------------------1---------------------");
    
    // 循环引用
    self.myBlock = ^{
        NSLog(@"block self = %lu",(unsigned long)[self retainCount]);
        
        NSLog(@"block weakSelf = %lu",(unsigned long)[weakSelf retainCount]);
        
        NSLog(@"---------------------2------------------");
        
        __strong typeof (weakSelf) strongSelf = weakSelf;
        
        NSLog(@"block self = %lu",(unsigned long)[self retainCount]);
        NSLog(@"block weakSelf = %lu",(unsigned long)[weakSelf retainCount]);
        NSLog(@"block strongSelf = %lu",(unsigned long)[strongSelf retainCount]);;
        
        NSLog(@"-----------------3----------------------");
        
        for (int i = 0; i < 5; i++) {
            NSLog(@"block self = %lu",(unsigned long)[self retainCount]);
        }
        
        for (int i = 0; i < 5; i++) {
            NSLog(@"block weakSelf = %lu",(unsigned long)[weakSelf retainCount]);
        }
        
        for (int i = 0; i < 5; i++) {
            NSLog(@"block strongSelf = %lu",(unsigned long)[strongSelf retainCount]);
        }
    };
    self.myBlock();
}
  • 运行结果
2019-06-09 15:02:38.065125+0800 WeakStrongSelfDemo[7175:182681] self1 内存地址:0x7ff4ddc41390 引用计数:9
2019-06-09 15:02:38.065280+0800 WeakStrongSelfDemo[7175:182681] weakSelf 内存地址:0x7ff4ddc41390 引用计数:11
2019-06-09 15:02:38.065368+0800 WeakStrongSelfDemo[7175:182681] self2 内存地址:0x7ff4ddc41390 引用计数:11
2019-06-09 15:02:38.065441+0800 WeakStrongSelfDemo[7175:182681] ------------------1---------------------
2019-06-09 15:02:38.065530+0800 WeakStrongSelfDemo[7175:182681] block self = 12
2019-06-09 15:02:38.065604+0800 WeakStrongSelfDemo[7175:182681] block weakSelf = 13
2019-06-09 15:02:38.065681+0800 WeakStrongSelfDemo[7175:182681] ---------------------2------------------
2019-06-09 15:02:38.065848+0800 WeakStrongSelfDemo[7175:182681] block self = 13
2019-06-09 15:02:38.066290+0800 WeakStrongSelfDemo[7175:182681] block weakSelf = 14
2019-06-09 15:02:38.066566+0800 WeakStrongSelfDemo[7175:182681] block strongSelf = 15
2019-06-09 15:02:38.066844+0800 WeakStrongSelfDemo[7175:182681] -----------------3----------------------
2019-06-09 15:02:38.067101+0800 WeakStrongSelfDemo[7175:182681] block self = 15
2019-06-09 15:02:38.067378+0800 WeakStrongSelfDemo[7175:182681] block self = 15
2019-06-09 15:02:38.067701+0800 WeakStrongSelfDemo[7175:182681] block self = 15
2019-06-09 15:02:38.067955+0800 WeakStrongSelfDemo[7175:182681] block self = 15
2019-06-09 15:02:38.068178+0800 WeakStrongSelfDemo[7175:182681] block self = 15
2019-06-09 15:02:38.068521+0800 WeakStrongSelfDemo[7175:182681] block weakSelf = 16
2019-06-09 15:02:38.068815+0800 WeakStrongSelfDemo[7175:182681] block weakSelf = 17
2019-06-09 15:02:38.069058+0800 WeakStrongSelfDemo[7175:182681] block weakSelf = 18
2019-06-09 15:02:38.069359+0800 WeakStrongSelfDemo[7175:182681] block weakSelf = 19
2019-06-09 15:02:38.069751+0800 WeakStrongSelfDemo[7175:182681] block weakSelf = 20
2019-06-09 15:02:38.070052+0800 WeakStrongSelfDemo[7175:182681] block strongSelf = 21
2019-06-09 15:02:38.084354+0800 WeakStrongSelfDemo[7175:182681] block strongSelf = 22
2019-06-09 15:02:38.084437+0800 WeakStrongSelfDemo[7175:182681] block strongSelf = 23
2019-06-09 15:02:38.084485+0800 WeakStrongSelfDemo[7175:182681] block strongSelf = 24
2019-06-09 15:02:38.084528+0800 WeakStrongSelfDemo[7175:182681] block strongSelf = 25
2019-06-09 15:06:01.899710+0800 WeakStrongSelfDemo[7175:182681] touchesBegan self 内存地址:0x7ff4ddc41390 引用计数:5
  • 接下来对运行结果分段进行分析
// 引用计数
for (int i = 0; i < 3; i++) {
    NSLog(@"self1 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
}

__weak typeof(self) weakSelf = self;
for (int i = 0; i < 3; i++) {
    NSLog(@"weakSelf 内存地址:%p",weakSelf);
}
NSLog(@"引用计数:%lu",(unsigned long)[weakSelf retainCount]);
NSLog(@"----------------0--------------");

for (int i = 0; i < 3; i++) {
    NSLog(@"引用计数:%lu",(unsigned long)[weakSelf retainCount]);
}

NSLog(@"self2 内存地址:%p 引用计数:%lu",self,(unsigned long)[self retainCount]);
NSLog(@"weakSelf 内存地址:%p 引用计数:%lu",weakSelf,(unsigned long)[weakSelf retainCount]);
  • 运行结果
2019-06-09 15:13:07.694736+0800 WeakStrongSelfDemo[7373:189509] self1 内存地址:0x7f93c9f065f0 引用计数:9
2019-06-09 15:13:07.694883+0800 WeakStrongSelfDemo[7373:189509] self1 内存地址:0x7f93c9f065f0 引用计数:9
2019-06-09 15:13:07.694978+0800 WeakStrongSelfDemo[7373:189509] self1 内存地址:0x7f93c9f065f0 引用计数:9
2019-06-09 15:13:07.695075+0800 WeakStrongSelfDemo[7373:189509] weakSelf 内存地址:0x7f93c9f065f0
2019-06-09 15:13:07.695166+0800 WeakStrongSelfDemo[7373:189509] weakSelf 内存地址:0x7f93c9f065f0
2019-06-09 15:13:07.695252+0800 WeakStrongSelfDemo[7373:189509] weakSelf 内存地址:0x7f93c9f065f0
2019-06-09 15:13:07.695336+0800 WeakStrongSelfDemo[7373:189509] 引用计数:13
2019-06-09 15:13:07.695410+0800 WeakStrongSelfDemo[7373:189509] ----------------0--------------
2019-06-09 15:13:07.695494+0800 WeakStrongSelfDemo[7373:189509] 引用计数:14
2019-06-09 15:13:07.695577+0800 WeakStrongSelfDemo[7373:189509] 引用计数:15
2019-06-09 15:13:07.695651+0800 WeakStrongSelfDemo[7373:189509] 引用计数:16
2019-06-09 15:13:07.695821+0800 WeakStrongSelfDemo[7373:189509] self2 内存地址:0x7f93c9f065f0 引用计数:16
2019-06-09 15:13:07.695990+0800 WeakStrongSelfDemo[7373:189509] weakSelf 内存地址:0x7f93c9f065f0 引用计数:18

通过运行结果可知,每次访问变量weakSelf(比如打印其内存地址,读取其引用计数[weakSelf retainCount]),都会使其引用计数+1。但是self不会。

  • 运行结果段 2 分析
weakSelf 内存地址:0x7f8e05e22ae0 引用计数:11
self2 内存地址:0x7f8e05e22ae0 引用计数:11  // 因为 self 和 weakSelf 指向同一块内存,所以他们的引用计数值相同
------------------1---------------------
block self = 12  // 因为 block 也强引用了 self,所以 self 的引用计数+1
block weakSelf = 13  // 访问了 [weakSelf retainCount],引用计数+1
---------------------2------------------
block self = 13  // 即weakSelf的引用计数 13
block weakSelf = 14  // 访问了 [weakSelf retainCount],引用计数+1
block strongSelf = 15  // 原理同weakSelf一样
  • 运行结果段 3 分析
2019-06-09 15:20:03.540679+0800 WeakStrongSelfDemo[7446:193548] block self = 15
2019-06-09 15:20:03.541845+0800 WeakStrongSelfDemo[7446:193548] block self = 15
2019-06-09 15:20:03.542679+0800 WeakStrongSelfDemo[7446:193548] block self = 15
2019-06-09 15:20:03.543429+0800 WeakStrongSelfDemo[7446:193548] block self = 15
2019-06-09 15:20:03.544483+0800 WeakStrongSelfDemo[7446:193548] block self = 15
2019-06-09 15:20:03.544844+0800 WeakStrongSelfDemo[7446:193548] block weakSelf = 16
2019-06-09 15:20:03.545132+0800 WeakStrongSelfDemo[7446:193548] block weakSelf = 17
2019-06-09 15:20:03.545381+0800 WeakStrongSelfDemo[7446:193548] block weakSelf = 18
2019-06-09 15:20:03.545757+0800 WeakStrongSelfDemo[7446:193548] block weakSelf = 19
2019-06-09 15:20:03.546010+0800 WeakStrongSelfDemo[7446:193548] block weakSelf = 20
2019-06-09 15:20:03.546266+0800 WeakStrongSelfDemo[7446:193548] block strongSelf = 21
2019-06-09 15:20:03.546596+0800 WeakStrongSelfDemo[7446:193548] block strongSelf = 22
2019-06-09 15:20:03.567575+0800 WeakStrongSelfDemo[7446:193548] block strongSelf = 23
2019-06-09 15:20:03.567672+0800 WeakStrongSelfDemo[7446:193548] block strongSelf = 24
2019-06-09 15:20:03.567725+0800 WeakStrongSelfDemo[7446:193548] block strongSelf = 25

原因在结果段 2 已经分析过了

前面都是从代码例子去佐证,接下来我们从底层原理角度去分析它

四 从底层原理角度分析
4.1 weakSelf
iOS-Block 中 为何使用 weakSelf 和 strongSelf_第3张图片
image.png
iOS-Block 中 为何使用 weakSelf 和 strongSelf_第4张图片
image.png
- (void)test5 {
    Student *stu = [[Student alloc] init];
    __weak Student *weakStu = stu;
    
    self.myBlock = ^{
        NSLog(@"%p",stu);
        NSLog(@"%p",weakStu);
    };
    self.myBlock();
}

// 在 block 内部存储数据格式
struct __main_block_impl_0 {
    NSObject *__weak weakStu;
}

block底层结构分析可知,一个被__weak修饰的局部变量,最终会被block捕获为自己的属性NSObject *__weak weakStu;

所以对weakSelf直白的理解就是结构体__main_block_impl_0weakSelf这个局部变量捕获作为了自己的属性。结构体直接引用了weakSelf内存空间,想使用weakself中保存的self指针,而这个weakSelf并没有增加self的引用计数,所以self依然可以释放。

4.2 strongSelf
__strong typeof (weakSelf) strongSelf = weakSelf;

最终转换为底层代码是

TestViewController *strongSelf = weakSelf;

并且执行block里面的代码,本质是执行一个函数__TestViewController__test_block_func_0。所以TestViewController *strongSelf = weakSelf;赋值得到的是self(由 weakSelf 传过来),这使得在函数体运行期间,self不会被释放。

既然是函数,那么大括号走完其函数体重的局部变量就会被释放,也就是说函数执行完以后,strongSelf作为局部变量正常释放了,strongSelf也不属于block结构体的属性,weakSelfstrongSelf一内一外,意义是不一样的。

借鉴网上的图


iOS-Block 中 为何使用 weakSelf 和 strongSelf_第5张图片
image
image

__strong 确保在 Block 内,strongSelf 不会被释放。

五 总结
__weak __typeof(self)weakSelf = self;    //1

[self.context performBlock:^{      
    [weakSelf doSomething];          //2
     __strong __typeof(weakSelf)strongSelf = weakSelf;  //3
    [strongSelf doAnotherSomething];        
}];
1.使用__weak __typeof是在编译的时候,另外创建一个局部变量weak对象来操作self,引用计数不变。block 会将这个局部变量捕获为自己的属性,
访问这个属性,从而达到访问 self 的效果,因为他们的内存地址都是一样的。

2.因为weakSelf和self是两个变量,doSomething有可能就直接对self自身引用计数减到0了.
  所以在[weakSelf doSomething]的时候,你很难控制这里self是否就会被释放了.weakSelf只能看着.

3.__strong __typeof在编译的时候,实际是对weakSelf的强引用.
  指针连带关系self的引用计数会增加.但是你这个是在block里面,生命周期也只在当前block的作用域.
  所以,当这个block结束, strongSelf随之也就被释放了.不会影响block外部的self的生命周期.

总结
在 Block 内如果需要访问 self 的方法、变量,建议使用 weakSelf。
如果在 Block 内需要多次 访问 self,则需要使用 strongSelf。


相关文章参考
透彻理解block中weakSelf和strongSelf
到底什么时候才需要在ObjC的Block中使用weakSelf/strongSelf


项目链接地址 - WeakStrongSelfDemo

你可能感兴趣的:(iOS-Block 中 为何使用 weakSelf 和 strongSelf)