How to print NSArray objects via for statement or enumeration?

29,116

Solution 1

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);

Solution 2

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);
}
Share:
29,116
Xtrician
Author by

Xtrician

iOS Developer

Updated on July 09, 2022

Comments

  • Xtrician
    Xtrician almost 2 years

    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.

  • Richard J. Ross III
    Richard J. Ross III over 12 years
    How was this accepted? I was just being a smart-ass
  • vikingosegundo
    vikingosegundo over 12 years
    Quite impressive. I am missing some bit-shifting…
  • fatuhoku
    fatuhoku almost 10 years
    Or direct bit-manipulation on the RAM chip by focussing the sun's rays onto the relevant memory cells with a magnifying glass
  • Dale Amon
    Dale Amon about 2 years
    Or someone could have answered his actual question and suggested: printf ("%s\n", [[a componentsJoinedByString: @"|"] cString]);