I read a CSV file into an array using:
NSString *theWholeTable = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"example" ofType:@"csv"]
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *tableRows = [theWholeTable componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
And every second object in the array is empty, any idea why?
the CSV file data looks like this: 10,156,326,614,1261,1890,3639,5800,10253,20914 20,107,224,422,867,1299,2501,3986,7047,14374
with 10 and 20 being the start of each new line.
thanks in advance.
Edit I tried using the following code instead:
NSArray *tableRows = [theWholeTable componentsSeparatedByString:@"\n"];
And that worked the way I wanted it too.
Although I am still unsure why the newlineCharacterSet created empty objects...
If your CSV file comes from a non-UNIX system, it may contain multiple line separators (e.g. \r\n instead of \n). In this case, componentsSeparatedByCharactersInSet will insert empty strings for empty character sequences between \r and \n.
You can remove empty strings from NSArray using this method:
tableRows = [tableRows filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
to solve this problem, I have used other way:
NSArray *tableRows = [theWholeTable componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\n"]]
So you wouldn't need remove any lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With