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

前端 未结 13 2423
南旧
南旧 2020-11-22 04:10

What does this line of code mean?

label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;

The ? and :

13条回答
  •  温柔的废话
    2020-11-22 04:20

    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!

提交回复
热议问题