Jacob Wood
Jacob Wood

Reputation: 467

parse csv in ios6

I have tried this method to parse csv and I am getting the value but If any field is in double quotes "" and has a comma within like "45,34,555" then its seperaing the value in 3 fields its just one field .How should I modify the below code to get the required result.

 NSMutableArray *contentArray = [NSMutableArray array];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"csv"];


    NSError*  error;
    NSString* Data = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error ];


    if (Data)
    {
        NSArray *myText = [Data componentsSeparatedByString:@","];
        NSInteger idx;
        for (idx = 0; idx < myText.count; idx++) {
            NSString *data =[myText objectAtIndex:idx];
            NSLog(@"%@", data);
            id x = [NSNumber numberWithFloat:0+idx*0.002777778];
            id y = [NSDecimalNumber decimalNumberWithString:data];
            [contentArray addObject:
             [NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y",nil]];
        }
        self.dataForPlot = contentArray;

    }

Upvotes: 0

Views: 137

Answers (1)

Cocoanetics
Cocoanetics

Reputation: 8245

You should look into NSScanner for this purpose. You need to detect if you are getting double quotes, if yes, then you scan until the closing quotes and treat this as a single unit. If you get a colon then you know that you got the next column.

Upvotes: 2

Related Questions