Nicely formatted data to debugger console for iPhone SDK

I was looking to be able see the data in one of my SQLite3 database tables on the iPhone in the console, but could not find a nice and easy way to do this. Here is my solution to the problem.

This routine is set up to take in an NSMutableArray corresponding to the rows of the tabular data, and each of the elements of the array is an NSMutableArray of the columnar data. All of the items in the column array need to be of type NSString, and the first element of the rows array should be a row of column headers. If you need other types or do not want to use a headers row, please feel free to modify the code as you see fit.

Here is the NSLogTable header and implementation files that I put together for this purpose:

//
//  NSLogTable.h
//
 
#import <Foundation/Foundation.h>
 
@interface NSLogTable : NSObject {
 
}
 
+ (void)dumpTable:(NSMutableArray *)rows;
 
@end
//
//  NSLogTable.m
//
 
#import "NSLogTable.h"
 
@implementation NSLogTable
 
+ (void)dumpTable:(NSMutableArray *)rows
{
	int idx = 0;
	NSMutableArray *rowData;
	int colWidths[100];
	NSString *s;
	NSMutableString *ms = [[NSMutableString alloc] init];
	BOOL firstRow = YES;
 
	for (int i = 0; i < 100; i++) colWidths[i] = 0;
 
	// get the maximum column widths
	for (id row in rows)
	{
		rowData = (NSMutableArray *)row;
		for (int i = 0; i < [rowData count]; i++)
		{
			s = [rowData objectAtIndex:i];
			if ([s length] > colWidths[i])
			{
				colWidths[i] = [s length];
			}
		}
	}
 
	for (id row in rows)
	{
		[ms setString:@""];
		if (firstRow)
		{
			[ms appendString:@"     "];
			firstRow = NO;
		} else {
			[ms appendFormat:@"%4d ", idx];
		}		
 
		rowData = (NSMutableArray *)row;
		for (int i = 0; i < [rowData count]; i++)
		{
			s = [rowData objectAtIndex:i];
			[ms appendString:[s stringByPaddingToLength:colWidths[i] withString:@" " startingAtIndex:0]];
			[ms appendString:@" "];
		}
 
		NSLog(@"%@", ms);
		idx++;
	}
}
 
@end

Once you build your rows array (make sure to import the NSLogTable.h file into your implementation file), you send it to the console like this, where theData is your NSMutableArray:

[NSLogTable dumpTable:theData];

As always, please keep in mind that there is minimal optimization and error checking going on in this code. If you have any suggestions, please let me know.

One Comment

  1. […] my utility class that outputs the contents of a SQLite3 database table (see my blog post entitled Nicely formatted data to debugger console for iPhone SDK), this is very annoying as it takes up a lot of the debugging console […]

Leave a Reply