title: How to safely remove object from a nsmutablearray while iterating through it?
body: <p>I am using a nsmutablearray in loop and want to remove its object (or assign <code>nil</code>) that has just traversed.
  But if I am doing so, I get an error as <code>&lt;__NSArrayM: 0x8c3d3a0&gt; was mutated while being enumerated.'</code> . The code is as below </p>
  
  <pre><code>- (TreeNode*)depthLimitedSearch:(TreeNode *)current costLimit:(int)currentCostBound {
  
  NSMutableArray *children=[NSMutableArray arrayWithArray:[current expandNodeToChildren]];
  for (TreeNode *s in children) {
      if (s.puzzleBox.isFinalPuzzleBox) {//checking for final puzzleBox
          return s;
      }
      /*exploredNodes++;
      if (exploredNodes %10000==0) {
          NSLog(@"explored nodes for this treshold-%d are %d",currentCostBound,exploredNodes);
      }*/
  
      int currentCost =[s.cost intValue]+[s.heuristicsCost intValue];
  
      if (currentCost &lt;= currentCostBound) {
          //[s.puzzleBox displayPuzzleBox];
  
          TreeNode *solution = [self depthLimitedSearch:s costLimit:currentCostBound];
          if (solution!=nil){//&amp;&amp; (bestSolution ==nil|| [solution.cost intValue] &lt; [bestSolution.cost intValue])) {
              bestSolution = solution;
              return bestSolution;
          }
      }else {
          if (currentCost &lt; newLimit) {
              //NSLog(@"new limit %d", currentCost);
              newLimit = currentCost;
          }
      }
      // here I want to free memory used by current child in children
      [children removeObject:s]
  }
  children=nil;
  return nil;
  }
  </code></pre>
  
  <p>and I have commented the place where I want to release the space used by the child.</p>