2012-02-13 39 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 

所有,當你已經在你的代碼到深夜盯着很好玩。