表达式-=
做了什么?
我花了最后一小时试图修复一个最终包含的错误 - =本身:
[self.myArray objectAtIndex:myButton.tag -= 1];
我不确定那个表达式是做什么的,它应该与+=
类似吗?
真正神秘的部分是,如果我NSLog()它,它会使我的结果变得不可思议:
NSLog(@"data with -=: %@", [self.myArray objectAtIndex:((UIButton *)sender).tag -= 1]);
当我评论那条线时,它的工作方式应该如此。如果我取消评论该行,我无法获得我想要的索引位置。我不是100%确定它对我的数组做了什么,但是当我记录它时,我没有理由想到它会影响代码的其他部分。
答案 0 :(得分:1)
- = 1是一项赋值操作。
x -= 1;
就像说
x = x - 1;
所以,如果你这样做(在伪代码中)
print(x = x - 1);
你可以看到你已经改变了x然后打印出来。
答案 1 :(得分:1)
说明:
[self.myArray objectAtIndex:myButton.tag -= 1];
-=
运算符lvalue -= rvalue
被解释为lvalue = lvalue - rvalue
。所以,在这里你的代码可以写成:
[self.myArray objectAtIndex:myButton.tag = myButton.tag - 1];
转让声明(=
)反过来评估其左侧,因此在将myButton.tag
减少一之后,它将被传递给objectAtIndex:
,就好像它是: / p>
myButton.tag = myButton.tag - 1;
[self.myArray objectAtIndex:myButton.tag]; // here myButton.tag is already decreased by one
答案 2 :(得分:1)
我确信每个人都会遇到这个问题,特别是当你的思想在其他地方时。
首先,所有其他答案都很好地解释了运算符-=
的作用。
当您将日志语句放入时,程序borked的原因是因为您已经将目标(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
当你深夜盯着你的代码时,一切都非常有趣。