下面是我使用的代码。如果我按addQuanity,m_label is set会显示一个而不是两个。如果我再次按addWuantity,m_label将显示2。按minusQuantity将m_label更改为3而不是2,但再次按minusQuanity将m_label更改为2。
谢谢你,莱恩
NSInteger counter = 1;
-(IBAction) addQuantity
{
if (counter > 9 )
return;
[m_label setText:[NSString stringWithFormat:@"%d",++counter]];
}
-(IBAction) minusQuantity
{
if (counter < 1 )
return;
[m_label setText:[NSString stringWithFormat:@"%d",--counter]];
}发布于 2012-02-27 12:25:02
您是否使用递增(++)和递减(--)运算符作为前缀或后缀?如果您将它们用作后缀(如您在问题标题中所示),它们将按照您所描述的那样运行。如果您将它们用作前缀(如您在问题正文中所示),则它们将按照您的预期运行。
当用作后缀时,表达式将返回变量的原始值,然后加/减一。
NSInteger counter = 1;
NSLog(@"%i", counter++); // will print "1"
// now counter equals 2当用作前缀时,表达式将加/减1,然后返回更新后的变量的值。
NSInteger counter = 1;
NSLog(@"%i", ++counter); // will print "2"
// now counter equals 2发布于 2012-02-27 13:27:47
节省一行代码,使您的程序逻辑更容易理解。
NSInteger counter = 1;
-(IBAction) addQuantity
{
if (counter <= 9 )
[m_label setText:[NSString stringWithFormat:@"%d",++counter]];
}
-(IBAction) minusQuantity
{
if (counter >= 1 )
[m_label setText:[NSString stringWithFormat:@"%d",--counter]];
}发布于 2012-02-27 12:22:19
而不是
[m_label setText:[NSString stringWithFormat:@"%d",--counter]];试一试
counter -=1;
[m_label setText:[NSString stringWithFormat:@"%d",counter]];https://stackoverflow.com/questions/9459879
复制相似问题