假设以下情况:
self.collectionViewController.didEndDisplayingCell = ^(CollectionViewCell *cell) {
[self doSomething];
};
Xcode会抱怨我不能在该方法中使用self,否则我将有一个保留周期。
然后是另一种情况。我创建了一个加载图像并在完成时运行的类,并将其称为
[[MyImageClass sharedInstance] loadImageFromUrl:url
runOnCompletion:^(UIImage *image) {
[self doSomething];
}];
在这种情况下Xcode不会抱怨,并且在块内使用self!
为什么?
答案 0 :(得分:0)
第一种情况:
self
对象保留对块对象的强引用。
反之亦然,块也保留self
个对象。 Since blocks capture their context, package it up, and carry it along for the ride, any reference to self (or implicit reference with an ivar) within a block also will capture a strong reference to self
。您可以参考此https://blackpixel.com/writing/2014/03/capturing-myself.html
所以,它会保留周期!