开发者

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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜