views:

729

answers:

7

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!

+9  A: 

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;
}
Barry Wark
uhh that was fast :) Thanks a lot.
rdesign
(update: Yuck! Reposting as an answer.)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:#define statusString (statusBool ? @"Approved" : @"Rejected")...then:[NSString stringWithFormat: @"Status: %@", statusString]This saves you from having to use and release local variables in if-else patterns. FTW!
Richard Bronosky
+1  A: 

It's the ternary if-then-else operator

klausbyskov
+2  A: 

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;
Dietrich Epp
+1  A: 

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;
Claus Broch
+2  A: 

It's the tertiary operator. It's basic form is:

condition ? valueIfTrue : valueIfFalse

Where the values will only be evaluated if they are chosen.

Sean
+1  A: 

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;
Brian
+2  A: 

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!

Richard Bronosky