带有块泄漏内存的ios递归调用

时间:2014-05-08 11:34:06

标签: ios recursion automatic-ref-counting block

我从完成块递归调用一个函数,这会增加内存占用量,这很可能导致一个块保留周期,以下是代码:

- (void)tick {

   if (counter > counterLimit) {
      [self finish];
      return;
   }

   counter++;

   context = [[Context alloc] init];

   //this is executed in another thread 
   [self.executer computeWithContext:(Context*)context completion:^(NSDictionary *dictionary, Context *context_)
   {

      [self handleResponse];

      [self tick];

   }];
}

1 个答案:

答案 0 :(得分:0)

self拥有执行者,执行者拥有该块,该块捕获自我强烈(与拥有相同的效果)。你有一个保留周期。

为self创建一个弱引用,并在块中专门使用它。

- (void)tick {
   // ...

   __weak typeof(self) weakSelf = self;
   [self.executer computeWithContext:(Context*)context completion:^(NSDictionary *dictionary, Context *context_)
   {
      typeof(weakSelf) strongSelf = weakSelf;
      if(strongSelf) { // ensure the receiver is still there to receive
          [strongSelf handleResponse];
          [strongSelf tick];
      }    
   }];
}