I have a simple object. It has several NSString properties (propertyA, propertyB, propertyC).
I have a string (read from a csv file) in the following form:
this is value A, this is value B, this is value C
another row A, another row B
Notice that the second row is missing the last property.
I want to parse the string into my object. Currently I’m grabbing a line from the csv file and then doing this:
MyObject *something = [[MyObject alloc] init];
NSArray *split = [line componentsSeparatedByString:@","];
if (something.count > 0)
something.propertyA = [split objectAtIndex:0];
if (something.count > 1)
something.propertyB = [split objectAtIndex:1];
if (something.count > 2)
something.propertyC = [split objectAtIndex:2];
This works well, but feels really horrible and hacky!
Has anyone got any suggestions for how I can improve the code?
Take a look at this tread about parsing CSV Where can I find a CSV to NSArray parser for Objective-C?
Dave DeLong wrote a CSV-parser library, you can find it here: https://github.com/davedelong/CHCSVParser
Hope this helps 🙂