counter ++ / counter--没有按预期工作

时间:2012-02-27 04:00:36

标签: ios ios5 uilabel

以下是我正在使用的代码。如果我按addQuanity m_label设置显示一个而不是两个。如果我再次按addWANTity 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]];
}

3 个答案:

答案 0 :(得分: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 :(得分: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]];
}

答案 2 :(得分:0)

而不是

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

尝试

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