[英]Objective-C ARC block __strong __weak
使用ARC
測試1:
@interface test01ViewController ()
@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);
@end
@implementation test01ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.navigationItem.title = @"test01";
[self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
[self doSomethingWithObj:obj];
}];
}
object( self
)具有對該塊的顯式強引用。 並且該塊對self
具有隱式的strong
引用。 這是一個周期,現在兩個對象都不會被正確釋放。
所以test1 dealloc
不調用。
測試2:
@interface test03ViewController ()
@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);
@end
@implementation test03ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.navigationItem.title = @"test03";
__weak test03ViewController *weakSelf = self;
[self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
__strong test03ViewController *strongSelf = weakSelf;
[strongSelf doSomethingWithObj:obj];
}];
}
__weakSelf-> __strongSelf,我認為與test1
沒什么區別,但是test2可以調用dealloc
。
為什么?
看看這個答案: https : //stackoverflow.com/a/28475562/543224
無論如何,對於這種模式,捕獲強大的引用對於在塊運行之前自我被釋放的情況沒有任何作用,這仍然可能發生。 它確實確保執行塊時不會釋放self。 如果該塊本身進行異步操作,這為發生該事件提供了窗口,則這很重要。
在第一種情況下,該塊捕獲變量self
,這是一個強引用(即,其類型為test01ViewController * __strong
)。
在第二種情況下,該塊捕獲了變量weakSelf
,它是一個弱引用(即,其類型為test03ViewController * __weak
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.