View Full Version : Newbie: Print contents of array to console

Feb 2, 2009, 12:42 PM
It's been a while since i programed mac last, how to I print an arbitrary array in human readable form like say var_dump does in php?

Or any other way of visualizing arrays?

Feb 2, 2009, 01:32 PM

Feb 2, 2009, 02:10 PM

cocoa, objective c.

I sometimes forget there is any other method :)

Feb 2, 2009, 03:55 PM
// one way
NSLog(@"array: %@", array);

// a second way
for (id obj in array)
NSLog(@"obj: %@", obj);

Feb 2, 2009, 04:05 PM
cocoa, objective c.

I sometimes forget there is any other method :)
do you want a GUI application or should the output go to the console?

If a Foundation tool is okay for you here is some code for you:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int i;

NSMutableArray *array = [[NSMutableArray alloc]init];
for (i=0;i<10;++i)
[array addObject:[NSString stringWithFormat:@"%d", (i*3)]];

for (id obj in array)

[array release];

[pool drain];
return 0;

Best regards

Feb 2, 2009, 04:26 PM
// one way
NSLog(@"array: %@", array);

This works for NSArrays. (as well as NSDictionaries, NSSets, etc.) If you have a plain C array, you'll have to write a loop to print each element. (This also assumes you know the size of the array.)

The %@ format specifier, more specifically, uses the output of the object's "description" method. Most Foundation and AppKit classes implement this method, so you can use it to print all kinds of objects and get meaningful output. (For example, -[NSArray description] returns an NSString composed of the descriptions of all its elements.)