Block详解——内存管理

Block详解——内存管理

前言

在日常使用Block进行编码时,我们都会注意避免循环引用。这篇文章主要是分析我们在Block中使用__weak和__strong到底发生了什么。为什么就能避免循环引用和一些Crash。

直接引用self

typedef void (^Block)(void);

@interface MyViewController ()

@property (nonatomic, copy) Block block;

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.block = ^{
        NSLog(@"self is %@", self);
    };
}

- (void)dealloc {
    NSLog(@"Released");
}

@end

上面的代码是一个自定义的Controller的内部实现,MyViewController的block引用了self,当MyViewController被执行popViewControllerAnimated之后,我们会发现dealloc中的** NSLog**会一直不执行,即MyViewController实例无法被释放。

struct __MyViewController__viewDidLoad_block_impl_0 {
  struct __block_impl impl;
  struct __MyViewController__viewDidLoad_block_desc_0* Desc;
  MyViewController *const __strong self;
  __MyViewController__viewDidLoad_block_impl_0(void *fp, struct __MyViewController__viewDidLoad_block_desc_0 *desc, MyViewController *const __strong _self, int flags=0) : self(_self) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};

static void __MyViewController__viewDidLoad_block_func_0(struct __MyViewController__viewDidLoad_block_impl_0 *__cself) {
  MyViewController *const __strong self = __cself->self; // bound by copy
}

通过编译MyViewController为C++代码,我们可以看到Block强引用了self(MyViewController实例,下同),同时Block作为的属性被强引用,这就导致了循环引用。

MyViewController *const __strong self;
MyViewController *const __strong self = __cself->self; // bound by copy

引用weakSelf

typedef void (^Block)(void);

@interface MyViewController ()

@property (nonatomic, copy) Block block;

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) weakSelf = self;
    
    self.block = ^{
        NSLog(@"WeakSelf is %@", weakSelf);
    };
}

- (void)dealloc {
    NSLog(@"Released");
}

@end

现在把Block里的self先在外部转为弱引用的weakSelf,MyViewController被执行popViewControllerAnimated之后,就会在控制台打印出“Released”。之前的循环引用问题就解决了。

struct __MyViewController__viewDidLoad_block_impl_0 {
  struct __block_impl impl;
  struct __MyViewController__viewDidLoad_block_desc_0* Desc;
  MyViewController *const __weak weakSelf;
  __MyViewController__viewDidLoad_block_impl_0(void *fp, struct __MyViewController__viewDidLoad_block_desc_0 *desc, MyViewController *const __weak _weakSelf, int flags=0) : weakSelf(_weakSelf) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __MyViewController__viewDidLoad_block_func_0(struct __MyViewController__viewDidLoad_block_impl_0 *__cself) {
  MyViewController *const __weak weakSelf = __cself->weakSelf; // bound by copy
}

之前被Block强引用的self现在变成弱引用的weakSelf

MyViewController *const __weak weakSelf;
MyViewController *const __weak weakSelf = __cself->weakSelf; // bound by copy

多数情况下,引用weakSelf是没问题的。但是在涉及到异步操作时,weakSelf有可能在使用前就已经被释放为nil,此时调用weakSelf作为参数的方法时,就会有crash的风险。比如下面的情况:

typedef void (^Block)(void);

@interface MyViewController ()

@property (nonatomic, copy) Block block;

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) weakSelf = self;
    
    self.block = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSMutableArray array] addObject:weakSelf];
        });
    };
    
    self.block();
}

- (void)dealloc {
    NSLog(@"Released");
}

@end

MyViewController被pushViewController后马上popViewController,当执行GCD里面的方法时,weakSelf已经为nil,这是就会引发Crash。

Weak-strong dance

typedef void (^Block)(void);

@interface MyViewController ()

@property (nonatomic, copy) Block block;

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) weakSelf = self;
    
    self.block = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSMutableArray array] addObject:weakSelf];
        });
    };
    
    self.block();
}

- (void)dealloc {
    NSLog(@"Released");
}

@end

Weak-strong dance是在Block的外部使用weakSelf弱引用self,然后在Block内部使用strongSelf强引用weakSelf,为了看看这个过程到底发生了什么,我们继续看MyViewController编译为C++后的代码。

struct __MyViewController__viewDidLoad_block_impl_0 {
  struct __block_impl impl;
  struct __MyViewController__viewDidLoad_block_desc_0* Desc;
  MyViewController *const __strong strongSelf;
  MyViewController *const __weak weakSelf;
  __MyViewController__viewDidLoad_block_impl_0(void *fp, struct __MyViewController__viewDidLoad_block_desc_0 *desc, MyViewController *const __strong _strongSelf, MyViewController *const __weak _weakSelf, int flags=0) : strongSelf(_strongSelf), weakSelf(_weakSelf) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __MyViewController__viewDidLoad_block_func_0(struct __MyViewController__viewDidLoad_block_impl_0 *__cself) {
  MyViewController *const __strong strongSelf = __cself->strongSelf; // bound by copy
  MyViewController *const __weak weakSelf = __cself->weakSelf; // bound by copy

  ((void (*)(id, SEL, ObjectType  _Nonnull __strong))(void *)objc_msgSend)((id)((NSMutableArray * _Nonnull (*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSMutableArray"), sel_registerName("array")), sel_registerName("addObject:"), (id _Nonnull)strongSelf);
}

struct __MyViewController__viewDidLoad_block_impl_1 {
  struct __block_impl impl;
  struct __MyViewController__viewDidLoad_block_desc_1* Desc;
  MyViewController *const __weak weakSelf;
  __MyViewController__viewDidLoad_block_impl_1(void *fp, struct __MyViewController__viewDidLoad_block_desc_1 *desc, MyViewController *const __weak _weakSelf, int flags=0) : weakSelf(_weakSelf) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __MyViewController__viewDidLoad_block_func_1(struct __MyViewController__viewDidLoad_block_impl_1 *__cself) {
  MyViewController *const __weak weakSelf = __cself->weakSelf; // bound by copy

  __attribute__((objc_ownership(strong))) typeof(weakSelf) strongSelf = weakSelf;

  dispatch_after(dispatch_time((0ull), (int64_t)(6 * 1000000000ull)), dispatch_get_main_queue(), ((void (*)())&__MyViewController__viewDidLoad_block_impl_0((void *)__MyViewController__viewDidLoad_block_func_0, &__MyViewController__viewDidLoad_block_desc_0_DATA, strongSelf, weakSelf, 570425344)));
}

因为这里涉及到嵌套Block,所以会生成两个Block的结构体。

__MyViewController__viewDidLoad_block_impl_1和__MyViewController__viewDidLoad_block_func_1

__MyViewController__viewDidLoad_block_impl_1持有的是MyViewController的弱引用MyViewController *const __weak weakSelf;

在__MyViewController__viewDidLoad_block_func_1函数中,__attribute__((objc_ownership(strong))) typeof(weakSelf) strongSelf = weakSelf;,这样在函数的作用域中MyViewController实例会被strongSelf指针强引用,引用数+1。即只要Block被执行,在执行期间MyViewController实例都不会被释放。函数执行完后,strongSelf指针会被回收,MyViewController实例被引用数-1。

__MyViewController__viewDidLoad_block_impl_0和__MyViewController__viewDidLoad_block_func_0

从上面的C++代码我们可以知道,嵌套的Block之间的关系不是外层Block引用内层Block,而是外层Block调用内层Block dispatch_after(dispatch_time((0ull), (int64_t)(6 * 1000000000ull)), dispatch_get_main_queue(), ((void (*)())&__MyViewController__viewDidLoad_block_impl_0((void *)__MyViewController__viewDidLoad_block_func_0, &__MyViewController__viewDidLoad_block_desc_0_DATA, strongSelf, weakSelf, 570425344)));

然后内层Block引用的外部变量,也是通过外层Block进行传递的。从__MyViewController__viewDidLoad_block_impl_0的MyViewController *const __strong strongSelf;可以看出内层Block对strongSelf是强引用。假设内层Block也是被Self强引用的,这样就会造成循环引用。所以内层Block需要创建自己的strongSelf来避免循环引用。

你可能感兴趣的:(Block详解——内存管理)