Why are all the other objects in my array empty?

I read the CSV file in 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?

CSV file data is as follows: 10,156,326,614,1261,1890,3639,5800,10253,20914 20,107,224,422,867,1299,2501,3986,7047,14374

where 10 and 20 are the beginning of each new line.

early.

Edit Instead, I tried using the following code:

 NSArray *tableRows = [theWholeTable componentsSeparatedByString:@"\n"]; 

And it worked the way I wanted it.

Although I'm still not sure why newlineCharacterSet created empty objects ...

+7
source share
2 answers

If your CSV file comes from a system other than UNIX, it may contain multiple line breaks (for example, \r\n instead of \n ). In this case, componentsSeparatedByCharactersInSet will insert blank lines for blank sequences of characters between \r and \n .

You can remove blank lines from NSArray with this method:

 tableRows = [tableRows filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]]; 
+9
source

to solve this problem, I used another way:

 NSArray *tableRows = [theWholeTable componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\n"]] 

Therefore, you will not need to delete rows.

+1
source

All Articles