Need Help With Simple Counting Bug in iPhone SDK
So I'm basically making an app that adds a 开发者_开发问答count to a number and then displays it each time you tap the button.
However, the first tap issued doesn't take any action but adds one (just as planned) on the second tap. I've searched to the ends of the earth looking for the solution with no luck, so I'll see what you guys can make of this. :)
#import "MainView.h"
@implementation MainView
int count = 0;
-(void)awakeFromNib {
counter.text = @"0";
}
- (IBAction)addUnit {
if(count >= 999) return;
NSString *numValue = [[NSString alloc] initWithFormat:@"%d", count++];
counter.text = numValue;
[numValue release];
}
- (IBAction)subtractUnit {
if(count <= 0) return;
NSString *numValue = [[NSString alloc] initWithFormat:@"%d", count--];
counter.text = numValue;
[numValue release];
}
@end
Actually the first tap is doing something.
You are post incrementing count
so on the first call to addUnit:
count
is incremented, but the return value of count++
is the old value of count. You want to preincrement with ++count
.
Example:
int count = 0;
int x = count++;
// x is 0, count is 1
x = ++count;
// x is 2, count is 2
精彩评论