I have the following problem in Objective-C using GCD I cannot figure out:

I am using the following method to calculate something for some 648 tiles.
The order of which tiles to process first is given by some algorithm setting the variable "pi". The variable "loaded" is global in this context and starts at 0 and correctly goes up to 647.

Everything works perfectly when not using the block.

```
while (loaded < [self.tiles count]) {
    long pi = /* tricky way to calculate the position index to set */;
    NSLog(@"loaded: %d", loaded);
    // Do this in a separate thread
    dispatch_async(loader, ^{
        NSLog(@"loaded ->: %d", loaded);
        [self.tiles[loaded] setPositionIndexTo:pi];
    });

    loaded++;
}

```

Problem:

I get an exception because the block tries to access self.tiles[648]!
In Apple's block documentation it sais, that the value of a variable inside the block is captured when the block is created, so I don't understand, how this is even possible. I do understand that the variable loaded in fact does have the value 648 in the end, which should abort the loop without executing. Some other weirdness is, that the value 0 is also never used in the block, but it starts out with 1. It is also sometimes possible to see that the block is ahead of the loop concerning the value of loaded, sometimes misses values at all, or does some twice. Here is some output:

```
 loaded ->: 612
 loaded: 613
 loaded ->: 613
 loaded ->: 614
 loaded: 614
 loaded ->: 614
 loaded: 615
 loaded: 616
 loaded ->: 615
 loaded: 617
 loaded ->: 617

```

Why and how is this possible?

Thanks for any clarification, as I think Apple's documents clearly state, that when the block is created, the value of "loaded" should be captured without being altered for the block anymore.