For in Objective-C
Objective-C provides several ways to create loops. Here are some basic types of loops.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// The most basic type, with a single condition.
int i = 1;
while (i <= 3) {
NSLog(@"%d", i);
i = i + 1;
}
// A classic initial/condition/after for loop.
for (int j = 0; j < 3; j++) {
NSLog(@"%d", j);
}
// Objective-C doesn't have a direct equivalent to Go's range over an integer,
// but we can use a for loop to achieve the same result.
for (int i = 0; i < 3; i++) {
NSLog(@"range %d", i);
}
// A while(true) loop will run repeatedly until you break out of the loop
// or return from the enclosing function.
while (true) {
NSLog(@"loop");
break;
}
// You can also continue to the next iteration of the loop.
for (int n = 0; n < 6; n++) {
if (n % 2 == 0) {
continue;
}
NSLog(@"%d", n);
}
}
return 0;
}
To run the program, compile it using a command like:
$ clang -framework Foundation for_example.m -o for_example
$ ./for_example
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
Objective-C uses while
, do-while
, and for
loops. The for
loop in Objective-C is similar to the C-style for
loop in Go. While Objective-C doesn’t have a direct equivalent to Go’s range
for integers, we can achieve similar functionality using standard for
loops.
The break
and continue
statements work similarly in Objective-C as they do in other C-derived languages, allowing you to exit a loop early or skip to the next iteration, respectively.
Note that Objective-C uses NSLog()
for console output instead of fmt.Println()
. Also, Objective-C requires the use of @autoreleasepool
for memory management in command-line programs.
We’ll see other forms of iteration later when we look at collections and other data structures in Objective-C.