Reading — step 1 of 5
Learn
Objective-C is C, so all C control flow works. Plus a few OC-specific constructs.
C-style if/else, switch, while, for
if (x > 0) {
NSLog(@"positive");
} else if (x < 0) {
NSLog(@"negative");
} else {
NSLog(@"zero");
}
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
switch (status) {
case 200: printf("ok\n"); break;
case 404: printf("not found\n"); break;
default: printf("other\n");
}
fast enumeration
OC's for (Type *item in collection) syntax — like Python's for-in:
NSArray *names = @[@"Ada", @"Bob", @"Carol"];
for (NSString *name in names) {
printf("%s\n", [name UTF8String]);
}
NSDictionary *ages = @{@"Ada": @36, @"Bob": @25};
for (NSString *name in ages) { %% iterates over keys
NSNumber *age = ages[name];
printf("%s: %d\n", [name UTF8String], [age intValue]);
}
Fast and clean. The compiler optimizes this to direct iteration without a method call per element.
BOOL — yes / no / true / false
Objective-C historically uses YES/NO. Modern OC also accepts true/false:
BOOL active = YES;
if (!active) {
NSLog(@"inactive");
}
BOOL is signed char (8-bit). For C++ interop or modern OC, prefer bool (one byte), but BOOL is the convention in Cocoa APIs.
Comparison
==compares POINTERS (object identity)[a isEqual:b]compares VALUES[a isEqualToString:b]for strings (slightly faster — skips type check)
NSString *a = @"hello";
NSString *b = [NSString stringWithFormat:@"%@", @"hello"];
a == b %% may or may not be YES (depends on string interning)
[a isEqual:b] %% YES (same content)
[a isEqualToString:b] %% YES (best for strings)
Nil checks
nil is the null pointer in OC. Sending a message to nil returns nil/0/NO — DOESN'T crash:
NSString *s = nil;
int len = [s length]; %% returns 0, no crash
This is unique to Objective-C. Most languages crash on null deref; OC silently returns the zero value. Both helpful and tricky.
Use explicit nil-checks when you need to distinguish:
if (obj == nil) {
NSLog(@"missing");
}
%% Or:
if (!obj) {
NSLog(@"missing");
}
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…