0

Possible Duplicate:
What does the question mark and the colon (?: ternary operator) mean in objective-c?

    NSString *requestString = (self.isFirstTimeDownload) ? [NSString stringWithFormat:[self.commonModel.apiURLs objectForKey:@"updateNewsVerPOST"],@""] : [NSString stringWithFormat:[self.commonModel.apiURLs objectForKey:@"updateNewsVerPOST"], [[NSUserDefaults standardUserDefaults] objectForKey:@"localnewsupdate"]];

Can anyone help me to understand what this is ()? and : in Objective-c? Thank you!!

Community
  • 1
  • 1
HYC
  • 69
  • 1
  • 1
  • 7
  • 3
    possible duplicate of [What does the question mark and the colon (?: ternary operator) mean in objective-c?](http://stackoverflow.com/q/2595392/), [What does this mean: NSString *string = NO ? @“aaa” : @“bbb”;](http://stackoverflow.com/q/8290073/), [Don't understand this syntax](http://stackoverflow.com/q/12132665/), [Objective-C operator (?) and (:)](http://stackoverflow.com/q/11705848/), [What does the “?” mean in the following statement?](http://stackoverflow.com/q/5832134/), [inactive ? @“inactive”: @“active” syntax?](http://stackoverflow.com/q/10239632/), – jscs Sep 26 '12 at 16:45

2 Answers2

4

That's a ternary operator.

Example:

  bool foo(int i)
  {
      if ( i > 5 ) 
          return true;
      else
          return false;
  }

is equivalent to

  bool foo(int i)
  {
      return ( i > 5 ) ? true : false;
  }

You can omit the first operand: x ? : b in which case, the value of the expression is x when x is non zero, or b otherwise. Example:

int i = 1;
i = 2 ? : 3;   // equivalent to i = 2; (because 2 is non zero)
i = YES ? : 3; // equivalent to i = 1; (because YES is 0x01, which is not zero)
Jano
  • 62,815
  • 21
  • 164
  • 192
Mahesh
  • 34,573
  • 20
  • 89
  • 115
0

It's a ternary operator:

NSString *requestString = ( boolean condition ) ? @"valueIfTrue" : @"valueIfFalse";
moonwave99
  • 21,957
  • 3
  • 43
  • 64