Hey guys,
Google just don't want to give me some useful results.
What does this line of code mean?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
The ? and : confuses me.
Thanks a lot!
Hey guys,
Google just don't want to give me some useful results.
What does this line of code mean?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
The ? and : confuses me.
Thanks a lot!
This is the C ternary operator (Objective-C is a superset of C):
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
is semantically equivalent to
if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}
This is part of C, so it's not Objective-C specific. Here's a translation into an if
statement:
if (inPseudoEditMode)
label.frame = kLabelIndentedRec;
else
label.frame = kLabelRect;
It's just a short form of writing an in-then-else statement. It means the same as the following code:
if(inPseudoEditMode)
label.frame = kLabelIndentedRect
else
label.frame = kLabelRect;
It's the tertiary operator. It's basic form is:
condition ? valueIfTrue : valueIfFalse
Where the values will only be evaluated if they are chosen.
That's just the usual ternary operator. If the part before the question mark is true, it evaluates and returns the part before the colon, otherwise it evaluates and returns the part after the colon.
a?b:c
is like
if(a)
b;
else
c;
Building on Barry Wark's excellent explanation...
What is so important about the ternary operator is that it can be used in places that an if-else cannot. ie: Inside a condition or method parameter.
[NSString stringWithFormat: @"Status: %@", (statusBool ? @"Approved" : @"Rejected")]
...which is a great use for preprocessor constants:
// in your pch file...
#define statusString (statusBool ? @"Approved" : @"Rejected")
// in your m file...
[NSString stringWithFormat: @"Status: %@", statusString]
This saves you from having to use and release local variables in if-else patterns. FTW!