美文网首页
block循环引用

block循环引用

作者: Berning | 来源:发表于2021-06-17 01:55 被阅读0次

循环引用

typedef void(^block)(void);

@interface NSPerson : NSObject

@property(nonatomic,assign)int age;

@property(nonatomic,copy)block block;
@end

int main()
{
        NSPerson *person = [[NSPerson alloc] init];
        person.block = ^{
        NSLog(@"person:%@",person);  //Capturing 'person' strongly in this block is likely to lead to a retain cycle
        };

        return 0;
}

ARC解决办法

  • __weak
int main()
{
        NSPerson *person = [[NSPerson alloc] init];
        __weak typeof(person) weakPerson = person;
        person.block = ^{
            NSLog(@"person:%@",weakPerson);
        };
}
  • __unsafe_unretained
int main()
{
                NSPerson *person = [[NSPerson alloc] init];
        __unsafe_unretained typeof(person) weakPerson = person;
        person.block = ^{
            NSLog(@"person:%@",weakPerson);
        };
}

  • __block
int main()
{
        __block NSPerson *person = [[NSPerson alloc] init];
        person.block = ^{
            NSLog(@"person:%@",person);
            person = nil;
        };
        
        person.block();
}
  • 对象作为参数
int main()
{
       NSPerson *person = [[NSPerson alloc] init];
       
       person.block = ^(NSPerson * _Nonnull person) {
           NSLog(@"person:%@",person);
       };
       person.block(person);
}

MRC解决办法

  • __block
    原理:__block不会对对象强引用
int main()
{
        __block NSPerson *person = [[NSPerson alloc] init];
        person.block = ^{
            NSLog(@"person:%@",person);
        };
        
        person.block();
}
  • __unsafe_unretained
int main()
{
                NSPerson *person = [[NSPerson alloc] init];
        __unsafe_unretained typeof(person) weakPerson = person;
        person.block = ^{
            NSLog(@"person:%@",weakPerson);
        };
}

相关文章

网友评论

      本文标题:block循环引用

      本文链接:https://www.haomeiwen.com/subject/ctprqktx.html