循环引用
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解决办法
- __block
原理:__block不会对对象强引用
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);
};
}
网友评论