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

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

n) 成了 oda sel pat some 系統 async efault

  • 系統的某些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];
      }];

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