Objective-C provides several mechanisms for iterating through an array. One can
- Iterate the array by index
- Use an iterator to walk the array
- Use the
for in
syntax
The dummy program below illustrates these methods.
If you are working from the command-line instead of from Xcode, the compilation line is
gcc -framework Foundation array.m -o array
array.m
#include <stdlib.h> #import <Foundation/Foundation.h> static void printArray1(NSArray *array) { size_t i = 0; size_t length = [array count]; for (i = 0; i < length; i++) { NSLog(@"%@", [array objectAtIndex: i]); } } static void printArray2(NSArray *array) { NSEnumerator *enumerator = [array objectEnumerator]; id object; while ((object = [enumerator nextObject]) != nil) { NSLog(@"%@", object); } } static void printArray3(NSArray *array) { for (id object in array) { NSLog(@"%@", object); } } int main(int argc, const char *argv[]) { int i; NSMutableArray *numbers; NSArray *sorted; numbers = [[NSMutableArray alloc] init]; for (i = 1; i < argc; i++) { [numbers addObject:[NSNumber numberWithInt:atoi(argv[i])]]; } NSLog(@"----------PRINT1----------------"); printArray1(numbers); NSLog(@"----------PRINT2----------------"); printArray2(numbers); NSLog(@"----------PRINT3----------------"); printArray3(numbers); return 0; }
No comments:
Post a Comment