title: iOS crash on device with ARC enabled
body: <p>I've hit a problem that has me completely stumped. I'll illustrate with a code sample:</p>
  
  <pre><code>@interface Crasher ()
  @property (nonatomic, strong) NSArray *array;
  @end
  
  @implementation Crasher
  
  - (void)crash;
  {
    NSMutableArray *mutable = [NSMutableArray array];
    NSArray *items = @[@0, @1, @2, @3];
  
    if ([@YES boolValue])
    {
      [items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [mutable addObject:obj];
      }];
    }
    else
    {
      [items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [mutable addObject:obj];
      }];
    }
  
    [self setArray:mutable];
  }
  
  @end
  </code></pre>
  
  <p>The above code crashes on the <code>[self setArray:mutable]</code> line when ARC is enabled and it is run on a device. The code never crashes on the simulator nor does it crash on a device with ARC disabled. Using <code>NSZombieEnabled</code> indicates that the setter is attempting to retain an already-deallocated array.</p>
  
  <p>It does not crash if the second <code>[mutable addObject:obj]</code> call is commented out (but this code is never executed in the first place).</p>
  
  <p>I've uploaded a project that demonstrates this crash to Github to <a href="https://github.com/aidansteele/arc-crash" rel="nofollow noreferrer"><code>aidansteele/arc-crash</code></a>. I am using Xcode 4.5.2. It seems to not occur on Xcode 4.6, but that is still in developer preview. What am I doing wrong?</p>
  
  <hr>
  
  <p>Addressing <a href="https://stackoverflow.com/a/13943891/216724">this</a> answer (in the question so that I have a bit more space), I don't believe the problem lies within <code>-[NSArray enumerateObjectsUsingBlock:]</code> as the problem persists if I change that method call to use the following <code>-[NSArray(Functional) each:]</code> call.</p>
  
  <pre><code>@interface NSArray (Functional)
  - (void)each:(void (^)(id obj))action;
  @end
  
  @implementation NSArray (Functional)
  
  - (void)each:(void (^)(id))action;
  {
    for (NSUInteger idx = 0; idx &lt; [self count]; idx++)
    {
      action([self objectAtIndex:idx]);
    }
  }
  
  @end
  </code></pre>