场景如下:
{
Person *person = [[Person alloc] init];
person.age = 10;
person.block = [^{
NSLog(@"age is %d", person.age);
}];
}
- 当离开作用域时,person对象销毁,所以“1”号线消失;
-
“2”、“3”因为是强引用,所以相互持有,对方都不会得到释放。
解决:
RAC 环境下:
-
__weak
:不会产生强引用,指向的对象销毁时,会自动让指针置为nil;
-
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);
}
-
__unsafe_unretained
:不会产生强引用,不安全,指向的对象销毁时,指针存储的地址值不变.
-
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
:必须添加对象 = ni
和调用block()
-
__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
__weak typeof(self) weakSelf = self;
MRC 环境下:
- MRC没有
__weak
- 用
__unsafe_unretained
解决; - 用
__block
解决.
__block id weakSelf = self;
self.block = ^ {
NSLog(@"age is %d", weakSelf);
}