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解决办法
- __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);
};
}