Archive for the ‘Source Code’ Category

Printing Tabular Data

July 31, 2010

So I have been working on a Core Data application for Mac OS X that will eventually have an iPhone and iPad. I have been learning how to write software in general and Cocoa code specifically along the way. A few days ago I started working on printing so I did what I always do when I need to learn a new piece and Google it. I found that there was very little out there on the subject, further what was there was fairly vague and mostly boiled down to ‘use WebKit and print that.’ I eventually found a little info that lead me to NSTextTable. Since I foresee making several applications that will need similar printing I decided to abstract as much code as possible out into it’s own class. My goal was to have a class that I could just hand over an array of objects (Core Data or not) and get a table back. I quickly discovered that I would have to send so much information to the class that it would be ridiculous, so I changed to an idea that just used strings.
I ended up with a class that I just had to create an array of arrays of strings to get an attributed string with a text table in it.
Since there is no little out on the web on this subject and I have gotten so much help from the web on some many other subjects I have decided to put my new class MSTablePrint out in to the world for anyone to use. I have given it the same license the Matt Gemmell uses for his source code (I literally copied it from his site and swapped out my name for his). This means that you are free to use this code in any project you want so long as you acknowledge my contribution. If you want for of a description just check out (Since I ‘borrowed’ the license from Mr. Gemmell I might as well link to his explanation (also feel free to check out the rest of his site while you’re there, he is _way_ smarter than me with this stuff).

To use this class you need to grab whatever objects you want in your table. Then create an array of strings from the keys you are interested in, in the order you want them to appear (the string at index 0 will end up in the first column). Once the strings are in an array add that array to another array. Whatever array is at index 0 will become the first row so if you want headers you should make them the first array. There are numerous other options you can set such as alternating row colors and header row styles that are all covered in the read me file in the zip file.

I will likely put up a tutorial in a few days using the Expenses application, but in the mean time feel free to post questions here so others can share in the answers.