iOS高级进阶

Block循环引用问题解析

2019-10-17  本文已影响0人  南城同學
场景如下:
{
     Person *person = [[Person alloc] init];
          person.age = 10;
          person.block = [^{
          NSLog(@"age is %d", person.age);       
     }]; 
}

解决:
RAC 环境下:
Person *person = [[Person alloc] init];
 __weak typeof(person) weakPerson = person;
 person.block = ^{
      NSLog(@"age is %d", weakPerson.age);
 };

__weak typeof(self) weakSelf = self;
self.block = ^{
    NSlog("%p",weakSelf);
}
Person *person = [[Person alloc] init];    
 __unsafe_unretained typeof(person) weakPerson = person;
 person.block = ^{
      NSLog(@"age is %d", weakPerson.age);
 };

__unsafe_unretained id weakSelf = self;
self.block = ^ {
    NSlog("%p",weakSelf);
}
__block Person *person = [[Person alloc] init];    
person.block = ^ {
      NSLog(@"age is %d", weakPerson.age);
      person = nil;
 };
person.block();

__block id weakSelf = self;
self.block = ^ {
      NSLog(@"age is %d", weakSelf);
      weakSelf = nil;
}
self.block();
首选:
 __weak typeof(self) weakSelf = self;

MRC 环境下:
__block id weakSelf = self;
self.block = ^ {
      NSLog(@"age is %d", weakSelf);
}
__block,为什么MRC环境下不需要再调用block() ?
上一篇 下一篇

猜你喜欢

热点阅读