使用系統的某些block api(如UIView的block版本寫動畫時),是否也考慮循環引用問題?


  • 系統的某些block api中,UIView的block版本寫動畫時不需要考慮,但也有一些api 需要考慮
  • 以下這些使用方式不會引起循環引用的問題
[UIView animateWithDuration:duration animations:^ { [self.superview layoutIfNeeded]; }]; [[NSOperationQueue mainQueue] addOperationWithBlock:^ { self.someProperty = xyz; }]; [[NSNotificationCenter defaultCenter] addObserverForName:@"someNotification" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * notification) { self.someProperty = xyz; }]; 
  • 但如果方法中的一些參數是 成員變量,那么可以造成循環引用,如 GCD 、NSNotificationCenter調用就要小心一點,比如 GCD 內部如果引用了 self,而且 GCD 的參數是 成員變量,則要考慮到循環引用,舉例如下:

    • GCD

      • 分析:self-->_operationsQueue-->block-->self形成閉環,就造成了循環引用
        __weak __typeof__(self) weakSelf = self; dispatch_group_async(_operationsGroup, _operationsQueue, ^ { [weakSelf doSomething]; [weakSelf doSomethingElse]; } ); 
    • NSNotificationCenter

      • 分析:self-->_observer-->block-->self形成閉環,就造成了循環引用
      __weak __typeof__(self) weakSelf = self; _observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"testKey" object:nil queue:nil usingBlock:^(NSNotification *note){ [weakSelf dismissModalViewControllerAnimated:YES]; }];


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM