我相信每個人在某個時間或某個時候都有這個問題,特別是當你的頭腦在別的地方時。
首先,所有其他答案很好地解釋了運營商-=
的功能。
當你把日誌語句放進去時,你的程序停止運行的原因是你減少了兩次目標(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