我相信每个人在某个时间或某个时候都有这个问题,特别是当你的头脑在别的地方时。
首先,所有其他答案很好地解释了运营商-=
的功能。
当你把日志语句放进去时,你的程序停止运行的原因是你减少了两次目标(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
所有,当你已经在你的代码到深夜盯着很好玩。
来源
2012-02-13 18:50:33
Jim
'x- = 1'等价于'x = x-1' – 2012-02-13 18:35:17
在第一个示例中,您的']]不是平衡的。 – dasblinkenlight 2012-02-13 18:37:04
' - ='*改变*左边的表达式并返回新的值,所以这就是为什么记录它会改变事物。 – Blorgbeard 2012-02-13 18:41:53