2012-02-27 143 views
2

下面是我使用的代码。如果我按addQuanity m_label设置显示一个而不是两个。如果我再次按addWuantity m_label显示2.按minusQuantity将m_label更改为3而不是2,但再次按minusQuanity将m_label更改为2.对我所缺少的任何想法?counter ++/counter--按预期工作

感谢, 瑞安

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]]; 
} 
+0

Try int counter =。 1 – Shubhank 2012-02-27 04:22:36

+0

Nitpicking;尝试重写你的标题, - 计数器与计数器不同(你的标题建议)。 – Jake 2012-02-27 16:36:22

回答

0

而不是

[m_label setText:[NSString stringWithFormat:@"%d",--counter]]; 

counter -=1; 
[m_label setText:[NSString stringWithFormat:@"%d",counter]]; 
3

您使用的是增量(++)和递减尝试( - )运算符作为前缀或作为后缀?如果您将它们用作后缀(如您在问题标题中所示),它们将按照您所描述的方式行事。如果您将它们用作前缀(如您在问题的正文中所示),那么它们将按照您的意愿行事。

当作为后缀使用时,表达式将返回变量的原始值,然后添加/减去一个。

NSInteger counter = 1; 
NSLog(@"%i", counter++); // will print "1" 
// now counter equals 2 

当用作前缀时,表达式将添加/减一,然后返回更新变量的值。

NSInteger counter = 1; 
NSLog(@"%i", ++counter); // will print "2" 
// now counter equals 2 
1

保存一行代码,使您的程序逻辑更易于理解。

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]]; 
}