Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

OldGit

macrumors newbie
Original poster
Feb 2, 2009
17
0
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?
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
Code:
// one way
NSLog(@"array: %@", array);

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

pstoehr

macrumors member
Hi,
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:
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
 

autorelease

macrumors regular
Oct 13, 2008
144
0
Achewood, CA
Code:
// 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.)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.