Where can I find a CSV to NSArray parser for Objective-C? [closed] Where can I find a CSV to NSArray parser for Objective-C? [closed] ios ios

Where can I find a CSV to NSArray parser for Objective-C? [closed]


I finally got around to cleaning up a parser I've had in my code folder and posted it on Github: http://github.com/davedelong/CHCSVParser

It's quite thorough. It handles all sorts of escaping schemes, newlines in fields, comments, etc. It also uses intelligent file loading, which means you can safely parse huge files in constrained memory conditions.


Here's a simple category on NSString to parse a CSV string that has commas embedded inside quote blocks.

#import "NSString+CSV.h"@implementation NSString (CSV)- (NSArray *)componentsSeparatedByComma{    BOOL insideQuote = NO;    NSMutableArray *results = [[NSMutableArray alloc] init];    NSMutableArray *tmp = [[NSMutableArray alloc] init];    for (NSString *s in [self componentsSeparatedByString:@","]) {        if ([s rangeOfString:@"\""].location == NSNotFound) {            if (insideQuote) {                [tmp addObject:s];            } else {                [results addObject:s];            }        } else {            if (insideQuote) {                insideQuote = NO;                [tmp addObject:s];                [results addObject:[tmp componentsJoinedByString:@","]];                tmp = nil;                tmp = [[NSMutableArray alloc] init];            } else {                insideQuote = YES;                [tmp addObject:s];            }        }    }    return results;}@end

This assumes you've read your CSV file into an array already:

myArray = [myData componentsSeparatedByString:@"\n"];

The code doesn't account for escaped quotes, but it could easily be extended to.


Quick way to do this:

NSString *dataStr = [NSString stringWithContentsOfFile:@"example.csv" encoding:NSUTF8StringEncoding error:nil];
NSArray *array = [dataStr componentsSeparatedByString: @","];