Newbie: Print contents of array to console

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

  1. macrumors newbie

    Joined:
    Feb 2, 2009
    #1
    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. macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
  3. thread starter macrumors newbie

    Joined:
    Feb 2, 2009
    #3
    cocoa, objective c.

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

    kainjow

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

    Joined:
    Aug 5, 2003
    Location:
    Scheßlitz, Oberfranken, Bavaria, Germany
    #5
    Hi,
    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:
    Code:
    #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)
    		NSLog(@"%@",obj);
    	
    	[array release];
    	
        [pool drain];
        return 0;
    }
    
    Best regards
    Peter
     
  6. macrumors regular

    Joined:
    Oct 13, 2008
    Location:
    Achewood, CA
    #6
    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