11

Possible Duplicate:
How do I iterate over an NSArray?

Here is my code (for example):

NSArray *myArray = [NSArray arrayWithObjects:@"Red", @"Blue", @"Green", nil];

I want loop through the array printing each string to the console.

Thanks.

Community
  • 1
  • 1
Xtrician
  • 504
  • 3
  • 5
  • 14

2 Answers2

28

The easiest way is just:

NSLog(@"%@", myArray);

Or, if you want to use fast enumeration to print each object in your own way:

for (NSString *string in myArray) {
    NSLog(@"%@", string);
}
Stuart
  • 36,683
  • 19
  • 101
  • 139
21

Let's find the most complex way, shall we?

NSArray *myArray = [NSArray array];
id *objects = malloc(sizeof(id) * myArray.count);
[myArray getObjects:objects range:NSMakeRange(0, myArray.count)];

char **strings = malloc(sizeof(char *) * myArray.count);

for (int i = 0; i < myArray.count; i++)
{
     strings[i] = [objects[i] UTF8String];
}

printf("<");
for (int i = 0; i < myArray.count; i++)
{
     printf("%s" strings[i]);
     if (i != myArray.count - 1)
         printf(", ");
}
printf(">");

free(objects);
free(strings);

Of course, you can always just do it like this:

NSLog(@"%@", myArray);
John Topley
  • 113,588
  • 46
  • 195
  • 237
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201