if, else if, and else
Objective-C inherits its conditional structure directly from C, so an if statement evaluates any expression that reduces to a scalar value: zero (or nil/NULL) is treated as false, and any nonzero value is treated as true. This means you can write if (someObject) to check for a non-nil pointer without an explicit comparison, though many teams prefer the more explicit if (someObject != nil) for readability in larger codebases.
Cricket analogy: It's like an umpire's binary decision on an lbw appeal: either the ball was going on to hit the stumps (true, out) or it wasn't (false, not out) — there's no in-between state, just like a scalar condition in C.
Because Objective-C's BOOL is typically a signed char (or the modern bool from stdbool.h on 64-bit runtimes), comparing BOOL values with == YES is a classic pitfall: if a BOOL is set from an expression that produces a value other than 0 or 1, the comparison can silently fail. The idiomatic style is to write if (isValid) or if (!isValid) rather than if (isValid == YES), treating the BOOL as the condition itself.
Cricket analogy: Trusting the third umpire's direct 'out' signal rather than re-checking it against a specific replay angle is like writing if (isOut) instead of if (isOut == YES) — you trust the boolean directly rather than over-specifying the comparison.
The ternary operator
The ternary operator condition ? valueIfTrue : valueIfFalse lets you assign a value based on a condition in a single expression, and Objective-C also supports the shorthand condition ?: valueIfFalse, which returns condition itself when it's truthy. This shorthand is especially handy for nil-coalescing patterns, such as NSString *name = userProvidedName ?: @"Guest";, which avoids repeating userProvidedName twice.
Cricket analogy: Setting a batting order with nextBatter = isOpenerOut ? reserveOpener : originalOpener; is exactly a ternary — one compact decision replacing a full if/else block, like a captain making a snap call at the toss.
switch statements
Objective-C's switch statement works on integer types (including enums, NSInteger, and unichar), and crucially does not support NSString or object comparisons directly — falling through to the next case unless you add a break is standard C behavior, and forgetting it is a common bug. A frequent, idiomatic use is switching over an NSInteger-backed enum like a UITableView section index or a custom typedef enum representing app state.
Cricket analogy: Switching on matchFormat (Test, ODI, T20) to decide the number of overs per innings is a natural switch statement, where forgetting break after the T20 case would wrongly fall through into ODI logic.
typedef NS_ENUM(NSInteger, AppState) {
AppStateLoading,
AppStateReady,
AppStateError
};
- (void)handleState:(AppState)state {
switch (state) {
case AppStateLoading:
NSLog(@"Loading...");
break;
case AppStateReady:
NSLog(@"Ready!");
break;
case AppStateError:
NSLog(@"Something went wrong.");
break;
default:
NSLog(@"Unknown state");
break;
}
// Ternary example with nil-coalescing shorthand
NSString *statusText = (state == AppStateReady) ? @"OK" : @"Not Ready";
NSString *displayName = self.userName ?: @"Guest";
NSLog(@"%@ - %@ (%@)", statusText, displayName, @(state));
}Objective-C's switch statement cannot switch directly on NSString objects because switch requires an integer-compatible expression. Attempting switch (someNSString) is a compile error; use a chain of if/isEqualToString: calls or map strings to an enum first.
NS_ENUM and NS_OPTIONS (from <Foundation/NSObjCRuntime.h>) are the modern, type-safe way to declare enums for use in switch statements, giving you compiler warnings when a switch doesn't handle every case.
- Any nonzero scalar (including a non-nil pointer) is treated as true in an if condition.
- Prefer
if (flag)/if (!flag)overif (flag == YES)to avoid BOOL comparison pitfalls. - The ternary operator
cond ? a : band its shorthandcond ?: bcompress simple if/else logic into one expression. a ?: breturnsaitself when truthy, making it useful for default/fallback values.- switch works only on integer-compatible types (including NS_ENUM values), never directly on NSString.
- Forgetting
breakcauses fall-through into the next case, a common and dangerous bug. - NS_ENUM gives compiler warnings for unhandled switch cases, improving safety over plain enums.
Practice what you learned
1. In Objective-C, what value does `if (somePointer)` treat as false?
2. Why is `if (isValid == YES)` considered risky style in Objective-C?
3. What does the expression `userProvidedName ?: @"Guest"` return when userProvidedName is nil?
4. Which of the following can a plain Objective-C switch statement directly switch on?
5. What happens if you omit `break` at the end of a switch case in Objective-C?
Was this page helpful?
You May Also Like
Loops in Objective-C
Understand Objective-C's for, while, do-while, and fast enumeration (for-in) loops, and how break and continue control iteration.
Methods and Message Passing
Explore how Objective-C methods work as messages sent to objects at runtime, including selectors, method signatures, and dynamic dispatch.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics