22
2011
Parsing CSV to Objective-C with CHCSVParser
Ever thought of how to import your excel data into iphone project? You can do it with CSV parser. CHCSVParser is an Objective-C parser for CSV files. It is very useful if you would like to import your data from excel file, you can save your excel to CSV format and import them into objective-c. The source can be downloaded from github here.
To use this library, in your controller, you need to import the “CHCSV.h” and implement its delegate like:
#import "CHCSV.h" @interface ViewController : UIViewController<CHCSVParserDelegate>
In the ViewController.m, implement the delegates like:
- (void) parser:(CHCSVParser *)parser didStartDocument:(NSString *)csvFile { } - (void) parser:(CHCSVParser *)parser didStartLine:(NSUInteger)lineNumber { } - (void) parser:(CHCSVParser *)parser didReadField:(NSString *)field { } - (void) parser:(CHCSVParser *)parser didEndLine:(NSUInteger)lineNumber { } - (void) parser:(CHCSVParser *)parser didEndDocument:(NSString *)csvFile { } - (void) parser:(CHCSVParser *)parser didFailWithError:(NSError *)error { }
For all the delegates above, the one that you might be interest in is the:
- (void) parser:(CHCSVParser *)parser didReadField:(NSString *)field
This delegate return each of the data in your CSV file, so you can retrieve and store the data in this delegate. For example you have a NSMutableArray called myArray, and you store each of the data into your array like:
- (void) parser:(CHCSVParser *)parser didReadField:(NSString *)field { [myArray addObject:field]; }
One thing you need to take note is that the CSV file must be in UTF-8 encoding, otherwise the parsing will be failed. Assume that you have your CSV file named “myCSV.csv”, you can parse the file like this:
NSError *error = nil; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"myCSV" ofType:@"csv"]; NSString *fileString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error]; if (fileString != nil) { CHCSVParser * p = [[CHCSVParser alloc] initWithCSVString:fileString encoding:NSUTF8StringEncoding error:&error]; [p setParserDelegate:self]; [p parse]; }
That’s it, simple right?
Related Posts
1 Comment + Add Comment
Leave a comment
Ads
Facebook Page
Categories
- Apache (1)
- Apps (2)
- Blog (19)
- IOS (20)
- IOS Library (5)
- iPhone Tutorial (17)
- Javascript (1)
- Node.js (1)
- Twitter (1)

An article by






Just wanted to say thanks for posting this info. I’m starting a personal project to learn iOS developing w/ a quiz program that has a large list of questions (which happen to be in an Excel file). I had been wondering how I was going to get the questions into iOS. This gives me a good start.