![](/img/trans.png)
[英]If a strong property has a block that refers to self, is that a retain cycle?
[英]Caputure property value lead to retain cycle through _property style
我有一堂課,這里有一個塊:
@property(nonatomic, strong) void (^hehe)();
在init方法中,我做了以下工作:
__weak test *weakSelf = self;
self.hehe = ^{
test *self = weakSelf;
NSLog(@"%zd", self.a);
NSLog(@"%zd", self->_a);
NSLog(@"%zd", _a);
};
該塊的最后兩行之間有什么區別。
我以為self->_a
等於_a
。
但是Xcode在最后一行顯示警告:
Caputuring self strongly in this block is likely to lead a retain cycle
編輯:
我知道本地自我和全球自我是不一樣的。 操作系統如何區分差異。 我使用clang重寫了代碼,並獲得了以下信息:
static void __ViewController__init_block_func_0(struct __ViewController__init_block_impl_0 *__cself) {
__Block_byref_weakSelf_0 *weakSelf = __cself->weakSelf; // bound by ref
ViewController *self = (weakSelf->__forwarding->weakSelf);
NSLog((NSString *)&__NSConstantStringImpl__var_folders_gp_6ztdfl3n5919c3y4pb03gd340000gn_T_ViewController_ad5b98_mi_0, ((NSInteger (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("a")));
NSLog((NSString *)&__NSConstantStringImpl__var_folders_gp_6ztdfl3n5919c3y4pb03gd340000gn_T_ViewController_ad5b98_mi_1, (*(NSInteger *)((char *)self + OBJC_IVAR_$_ViewController$_a)));
NSLog((NSString *)&__NSConstantStringImpl__var_folders_gp_6ztdfl3n5919c3y4pb03gd340000gn_T_ViewController_ad5b98_mi_2, (*(NSInteger *)((char *)self + OBJC_IVAR_$_ViewController$_a)));
}
最后兩行使用相同的self ...
因為這意味着不同的self
。 快速重命名將使一切變得清晰:
__weak test *weakSelf = self;
self.hehe = ^{
test *strongSelf = weakSelf;
NSLog(@"%zd", strongSelf.a);
NSLog(@"%zd", strongSelf->_a);
NSLog(@"%zd", _a);
};
現在很清楚,最后一行從塊外部捕獲了self
。 你有它命名方式,使得它更難於區分self
,這是一個塊內聲明的局部變量,並self
認為是從它的范圍之內拍攝的。
引用_a是從封閉范圍直接引用實例變量。 那暗含了自我。 它不會調用屬性的getter / setter。 它直接指向實例變量。
不要在一個持久的塊內執行此操作。 (Apple開始調用它時,這是一個“轉義”塊。)使用他的答案中顯示的weakSelf / strongSelf語法@Losiowaty。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.