cyclingIsBetter
cyclingIsBetter

Reputation: 17591

objective c: read a csv file

I have this type of file:

@firstTablel: 1#one#two#three#four; 2#apple#tower#flower#robot;

this is an example of my csv file..."firstTable" is my table and 1 and 2 are two id of my two item.

How I can read this file in objective c? Can you help me?

Upvotes: 2

Views: 10727

Answers (1)

Stephen Poletto
Stephen Poletto

Reputation: 3655

Cocoa for Scientists has a great post on reading CSV files: http://macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data

In your case, you'd do something like:

NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:outError];
if (!fileString) {
    NSLog(@"Error reading file.");
}
NSScanner *scanner = [NSScanner scannerWithString:fileString];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n#; "]];

NSString *id = nil, *hashOne = nil, *hashTwo = nil, *hashThree = nil, *hashFour = nil;
while ([scanner scanUpToString:@"#" intoString:&id] && [scanner scanUpToString:@"#" intoString:&hashOne] && [scanner scanUpToString:@"#" intoString:&hashTwo] && [scanner scanUpToString:@"#" intoString:&hashThree] && [scanner scanUpToString:@";" intoString:&hashFour]) {
     // Process the values as needed.
     NSLog(@"id:%@, 1:%@, 2:%@, 3:%@:, 4:%@", id, hashOne, hashTwo, hashThree, hashFour);
}

On the sample you've provided, this will print:

2011-03-31 13:55:07.846 Stephen[39304:903] id:1, 1:one, 2:two, 3:three:, 4:four
2011-03-31 13:55:07.849 Stephen[39304:903] id:2, 1:apple, 2:tower, 3:flower:, 4:robot

Upvotes: 11

Related Questions