Write CSV Data with iOS and Mac OS X
Write CSV Data with iOS and Mac OS X
Friday, November 18, 2011
Character Separated Value (CSV) text files are the lowest common cross platform denominator format
for exchanging tabular data.
With the code offered below, you can create CSV data in UTF-8 encoding from your objects using
Key-Value-Coding (KVC) and save those to files or the network.
Unfortunately, many CSV features have never been formally specified. Therefore, this code
standardizes on UTF-8 as character encoding and also produces a header line, containing column
headers, corresponding to KVC keys. It also handles quoting correctly so you can encode any string,
including ones containing field delimiter chars.
The interface is as simple as this, using two categories: @interface NSData (OPCSVParsing) /*"
Returns an enumerator returning one NSDictionary object per row, keyed by the names given,
containing the strings contained that the row. If no keys array is given, keys are taken from the first
row of the csv file. "*/ - (NSEnumerator*) csvDictionaryEnumeratorWithKeys: (NSArray*)
columnNames fieldDelimiter: (unsigned char) delimiter; @end @interface
NSEnumerator (OPCSVGeneration) /*" Produces (and returns) UTF-8 encoded CSV data with one
row (record) for each object enumerated. Each column entry is produced by calling -valueForKey
and -description on each key on the current object. Field delimiter is typically ',', ';' or '\t'.
Quoting is handeled correctly. "*/ - (NSData*) csvDataForElementKeys: (NSArray*) keys
withFieldDelimiter: (unsigned char) delimiter; @end
Similar code has been used in commercial products in the past.
Download the code, covered by the LGPL license.
Have fun!
Page 1/1