蘋果對編譯器也在不斷優化,GCD方法中的block基本都不需要使用weakself,并不會造成回圈參考, dispatch_after官方檔案中對block部分的說明:
一:使用self
從ViewControllerA push 到 ViewControllerB,ViewControllerB中代碼:
#import "ViewControllerB.h" @interface ViewControllerB () @end @implementation ViewControllerB - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor blueColor]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self log]; }); [self.navigationController popViewControllerAnimated:YES]; } - (void)log { NSLog(@"Finish"); } - (void)dealloc { NSLog(@"dealloc"); }
輸出結果

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"pop action"); __weak ViewControllerB *weakself = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [weakself log]; }); [self.navigationController popViewControllerAnimated:YES]; }
輸出結果

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"pop action"); __weak ViewControllerB *weakself = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ __strong ViewControllerB *strongself = weakself; [strongself log]; }); [self.navigationController popViewControllerAnimated:YES]; }
結果與使用weakself相同,
四:結論
1:上述代碼中,如果去除[self.navigationController popViewControllerAnimated:YES]操作,三種方法都能夠正常完成任務,
2:當block時間內,如果回傳上一頁面或其他類似操作,導致當前ViewController消失時,
使用self,ViewController會被block強參考,block時間截止完成回呼后,釋放block,進而釋放ViewController,
使用weakself時,不存在強參考,ViewController會被直接銷毀,
3:weak-strong dance,在dispatch_after中并沒有實際意義,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/271199.html
標籤:iOS
上一篇:Swift 進階(六)屬性
下一篇:Swift 進階(一)基礎語法
