Newbie: Print contents of array to console

Discussion in 'Mac Programming' started by OldGit, Feb 2, 2009.

  1. OldGit macrumors newbie

    Feb 2, 2009
    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?
  2. OldGit thread starter macrumors newbie

    Feb 2, 2009
    cocoa, objective c.

    I sometimes forget there is any other method :)
  3. kainjow Moderator emeritus


    Jun 15, 2000
    // one way
    NSLog(@"array: %@", array);
    // a second way
    for (id obj in array)
        NSLog(@"obj: %@", obj);
  4. pstoehr macrumors member

    Aug 5, 2003
    Scheßlitz, Oberfranken, Bavaria, Germany
    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
  5. autorelease macrumors regular

    Oct 13, 2008
    Achewood, CA
    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.)

Share This Page