How does "item.enabled = item2.enabled = item3.enabled = value" work?
Feeling like less-code-is-better-code so wanted to "optimize" how to enable seve开发者_运维问答ral items at the same time:
button1.enabled = YES;
button2.enabled = YES;
textField.enabled = YES;
...using this code. But what does it actually do? I believe button2 enabled state will be defined by result of setting textField enabled state? If textField case fails for unknown reason, then button1 would get result of operation of setting button2 enabled status?
At least in theory textField.enabled could be whatever, button2.enabled NO and button1.enabled YES ?!?!?
button1.enabled = button2.enabled = textField.enabled = YES;
What could go wrong? Is this safe at all?
The trick is that assignment is also an expression in C. Its value is the value that’s stored to the variable being assigned to. In other words, foo = 5
assigns 5
to foo
and the whole expression has value 5
.
This feature leads to some shortcuts similar to yours, the most famous one being probably while (*dst++ = *src++)
to copy a null-terminated string src
to dst
. In Objective-C you can often see the feature in the initializers:
- (id) init {
if !(self = [super init]) // self = super init; self == nil?
return nil;
…
return self;
}
Notice the single =
, that’s not a bug. But since it can be a great source of bugs (when you really meant ==
), modern compilers will often warn about the assignment and you have to enclose it in another pair of braces to silence the warning: if ((self = [super init]))
.
Yes, it's safe. You will set to YES
all properties before =
.
If I'm not mistaken operations are performed from right to left:
textField.enabled
will be equal to YESbutton2.enabled
will be equal to result of operationtextField.enabled = YES;
that will beYES
button1.enabled
wil be equal tobutton2.enabled = YES;
that will be equal toYES
(from 2) )
精彩评论