views:

109

answers:

1

I have the following code

-(void) animate:(UIButton*) b withState: (int) state andLastState:(int) last_state {
 if (state < last_state) {
     int stateTemp = state;
     float duration = 1.0 / 30.0;
     [b animateWithDuration: duration
         animations: ^{ [UIImage imageNamed:[NSString stringWithFormat:@"m1.a000%d.png", state]]; }
    completion: ^{ animate(b, stateTemp++, last_state); }];
     }

}

but get an error increment of read-only variable 'stateTemp'

I am trying to animate a series of images by setting a UIButtons image.

What is wrong with this code?

Thanks

+1  A: 

Any variable used inside a block is const copied. So really what you've got going on is this:

-(void) animate:(UIButton*) b withState: (int) state andLastState:(int) last_state {
if (state < last_state) {
 int stateTemp = state;
 float duration = 1.0 / 30.0;
 [b animateWithDuration: duration
     animations: ^{
      [UIImage imageNamed:[NSString stringWithFormat:@"m1.a000%d.png", state]];
     }
     completion: ^{
      const int stateTempCopy = stateTemp;
      animate(b, stateTempCopy++, last_state); 
     }
 ];
 }
}

The problem is trying to alter a const variable. You can't do that. Fortunately, there's a way around that, and that's with the __block specifier.

Simply change int stateTemp = state; to __block int stateTemp = state; and you'll be good to go. (For the documentation on __block, check out the documentation)

Dave DeLong