[英]How to keep a strong reference inside of a block without having a retain cycle
[英]weak variable with a strong reference in a block: does not create a retain cycle?
當我們將弱引用傳遞給塊內部的強引用時,為什么它起作用? 如果保留了塊中的局部變量,是否應該向self
添加一個保留,從而造成這個不良的保留周期?
這是示例:
__weak id weakSelf = self;
[self.operationQueue addOperationWithBlock:^{
NSNumber* result = findLargestMersennePrime();
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
MyClass* strongSelf = weakSelf;
strongSelf.textLabel.text = [result stringValue];
}];
}];
創建或復制一個塊時(例如,在將其調度到gcd時可以復制它),將捕獲引用的變量(除非使用__block指定符聲明)。 保留強引用,弱引用不保留。
當您創建局部strongSelf
變量時,它會在執行塊時使self
保持活動狀態(即,不執行且位於屬性中的對象沒有強引用)。 當您引用self
直接- self
被捕獲並保留下來,現在它保持self
,而塊是活的 。
__weak id weakSelf = self;
[self.operationQueue addOperationWithBlock:^{
NSNumber* result = findLargestMersennePrime();
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
MyClass* strongSelf = weakSelf; // strong reference when block executes
[self foo]; // strong reference when block created/copied
strongSelf.textLabel.text = [result stringValue];
}];
}];
看到不同? 如果您使用直接self
引用殺死所有指向對象的強指針,則在塊內仍然存在一個強引用,該強引用被捕獲並保留。 同時,本地strongSelf
指針僅在執行塊時持有對self
強引用,因此,如果self
已死,則weakSelf
將為nil, strongSelf
將獲得nil值。
不,這不會產生循環,因為自我沒有被捕捉為強者! :)
strongSelf是一個強引用,可保留self BUT,因為strongSelf是本地var,在完成塊時釋放它,並且保留計數下降
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.