block循环引用

2021-06-17  本文已影响0人  Berning

循环引用

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解决办法

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

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解决办法

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

上一篇下一篇

猜你喜欢

热点阅读