2012-02-13 40 views
-2

表达式-=是做什么的?- =运算符是做什么的?

我度过了最后一个小时试图修复该结束了,包括错误 - =本身:

[self.myArray objectAtIndex:myButton.tag -= 1]; 

我不知道那表情做什么,是不是应该是类似于+=

而真正令人困惑的部分是,如果我的NSLog(),它borks我的结果:

NSLog(@"data with -=: %@", [self.myArray objectAtIndex:((UIButton *)sender).tag -= 1]); 

当我的评论只是线路输出,它的工作原理像它应该。如果我取消注释该行,我无法获得我想要的索引位置。我不是100%确定它对我的数组有什么作用,但是当我刚刚记录它时,我没有理由想到它会影响代码的其他部分。

+1

'x- = 1'等价于'x = x-1' – 2012-02-13 18:35:17

+1

在第一个示例中,您的']]不是平衡的。 – dasblinkenlight 2012-02-13 18:37:04

+1

' - ='*改变*左边的表达式并返回新的值,所以这就是为什么记录它会改变事物。 – Blorgbeard 2012-02-13 18:41:53

回答

1

解释:

[self.myArray objectAtIndex:myButton.tag -= 1]; 

-=操作lvalue -= rvalue被解释为lvalue = lvalue - rvalue。所以,在这里你的代码可以写为:

[self.myArray objectAtIndex:myButton.tag = myButton.tag - 1]; 

赋值语句(=),反过来,评估它的左侧,因此通过减少1 myButton.tag后,它会被传递给objectAtIndex:,如果它是:

myButton.tag = myButton.tag - 1; 
[self.myArray objectAtIndex:myButton.tag]; // here myButton.tag is already decreased by one 
+0

d'oh!是任务方面。因为在nslog代码行中,我将button.tag(比如5)值重新赋值为-1,然后我将新的tag值设为4,减少1,当我还想索引时,这是3还有,我想我没意识到你可以在nslog stmt中重新赋值。 = /但我确实看到它是如何工作的,谢谢! – Padin215 2012-02-13 18:44:09

+0

没有问题。接受? – 2012-02-13 18:45:04

+0

我试过了,说我需要等5分钟。 – Padin215 2012-02-13 18:47:12

1

- = 1是一个赋值操作。

x -= 1; 

好像是说

x = x - 1; 

所以如果你(在伪代码)

print(x = x - 1); 

你可以看到你已经改变了X,则它打印。

+0

是的,错过了作业部分,谢谢 – Padin215 2012-02-13 18:45:57

+0

没问题.4321 – Almo 2012-02-13 19:00:56

1

我相信每个人在某个时间或某个时候都有这个问题,特别是当你的头脑在别的地方时。

首先,所有其他答案很好地解释了运营商-=的功能。

当你把日志语句放进去时,你的程序停止运行的原因是你减少了两次目标(tag)。

NSLog(@"data with -=: %@", [self.myArray objectAtIndex:((UIButton *)sender).tag -= 1]); // this decrements that target the first time 
[self.myArray objectAtIndex:myButton.tag -= 1]]; // this also decrements the target the second time 

您应该做这种方式

NSLog(@"data with -=: %@", [self.myArray objectAtIndex:((UIButton *)sender).tag]); // this logs the value before the decrement 
[self.myArray objectAtIndex:myButton.tag -= 1]]; // this decrements the target once 

或这样

[self.myArray objectAtIndex:myButton.tag -= 1]]; // this decrements the target once 
NSLog(@"data with -=: %@", [self.myArray objectAtIndex:((UIButton *)sender).tag]); // this logs the value after the decrement 

您可能也有兴趣++和 - 运营商由1递增和递减。阅读这些以避免错误地使用它们!你的情况,你可以这样做:

[self.myArray objectAtIndex:--myButton.tag]]; // this decrements the target before using it as an index 

但不是这样的:

[self.myArray objectAtIndex:myButton.tag--]]; // this decrements the target after using it as an index 

所有,当你已经在你的代码到深夜盯着很好玩。