關於iOS Block當中爲何要用weakSelf和strongSelf的思考

  場景:當你在某個界面請求網絡數據的時候,用戶不肯意等待點擊了返回按鈕,此時在Block當中用以下的方式使用weakSelf的話,有可能會奔潰(由於在併發編程的狀況下,雖然在if判斷的時候weakself不爲空,可是不保證if語句裏面的weakself不爲空),因此爲了安全起見要加上strongSelf(參考)。ios

if (weakSelf != nil) {
       // last remaining strong reference released by another thread. 
       // weakSelf is now set to nil.
       [myArray addObject:weakSelf];
}

  那爲何加上strongSelf就能夠保證self不爲空了?編程

  由於若是self有效,那麼strongself就是利用了循環引用的特性保證了在block執行的時候self對象不會被析構,strongSelf是局部變量執行完成後就會釋放安全

 

  接下來用個Demo驗證下,在FirstVC的ViewDidLoad裏面添加如下代碼網絡

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (0.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController pushViewController:[SecondVC new] animated:NO];
    });
    
    //0.025 - 0.03
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (0.55 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:NO];
    });

 

  而後在 SecondVC的 裏面添加如下代碼併發

  

typedef void(^TTestBlock)(int result);

@interface SecondVC ()
@property (strong, nonatomic)  TTestBlock  aBlock ;
@end

@implementation SecondVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self testForBlock];
}

- (void)testForBlock{
    
    __weak typeof(self) wSelf = self;
    self.aBlock = ^(int result) {
        
        NSLog(@"testForBlock:%@",wSelf);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            //沒有下面這一行的話,testForBlock2 中的self爲空
            __strong typeof(wSelf) strongSelf = wSelf;
            
            NSLog(@"testForBlock1:%@",wSelf);

            [NSThread sleepForTimeInterval:1];

       //__strong typeof(wSelf) strongSelf = wSelf;  //放在這兒的話也wSelf會爲空
            NSLog(@"testForBlock2:%@",wSelf);
        });
    } ;
    self.aBlock(0);
}
@end

 

 

注意:async

  • 關於Masonry裏面的Block:函數參數裏面的Block是局部的block(棧上),block內部引用self不會形成循環引用;是否會循環引用只看函數內部是否copy了這個block(好比把它付給全局的Block)(參考
  • 關於IBOutlet的weak:由於xib裏面的根視圖已經強引用了拖拽上去的UI控件了,因此拖拽到VC裏面用weak就行(參考
  • 關於weak的實現原理:Runtime維護了一個weak(hash)表,用於存儲指向某個對象的全部weak指針;當對象的強引用計數爲0的時候,會找到該對象的全部weak指針,將它置爲nil。
相關文章
相關標籤/搜索