Range Over Channels in Objective-C

In a previous example, we saw how loops provide iteration over basic data structures. In Objective-C, we can use similar syntax to iterate over values received from various collection types.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // We'll iterate over 2 values in the queue array.
        NSMutableArray *queue = [NSMutableArray arrayWithObjects:@"one", @"two", nil];
        
        // This for-in loop iterates over each element in queue.
        // Because we're using an array, the iteration terminates 
        // after accessing all elements.
        for (NSString *elem in queue) {
            NSLog(@"%@", elem);
        }
    }
    return 0;
}

To run the program, compile and execute it:

$ clang -framework Foundation objc_range_over_array.m -o objc_range_over_array
$ ./objc_range_over_array
2023-06-09 12:34:56.789 objc_range_over_array[12345:67890] one
2023-06-09 12:34:56.790 objc_range_over_array[12345:67890] two

This example demonstrates iterating over an array in Objective-C. While Objective-C doesn’t have channels like Go, we can use similar iteration techniques with various collection types such as NSArray, NSSet, or NSDictionary.

It’s worth noting that Objective-C uses Automatic Reference Counting (ARC) for memory management, which is different from Go’s garbage collection. In this example, we use an @autoreleasepool to ensure proper memory management of temporary objects.

For more complex scenarios involving asynchronous operations or producer-consumer patterns, you might consider using Grand Central Dispatch (GCD) or NSOperationQueue, which provide powerful concurrency abstractions in Objective-C.