2011-03-31 128 views
2

我有這種類型的文件:objective c:讀取csv文件

@firstTablel:1#one#two#three#four; 2#蘋果#塔#花#機器人;

這是我的csv文件的示例...「firstTable」是我的表格,1和2是我的兩個項目的兩個id。

如何在目標c中讀取此文件?你可以幫我嗎?

+7

這看起來並不像一個「逗號分隔值」文件... – 2011-03-31 17:31:15

回答

12

可可科學家們有一個偉大的職位上閱讀的CSV文件:http://macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data

在你的情況,你會做這樣的事情:

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); 
} 

在您所提供的樣品,這將打印:

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

你沒有處理好「@firstTablel:」。除此之外,這是要走的路。 – ughoavgfhw 2011-03-31 18:48:40

+0

但pahtfile?我的csv是在我的項目文件夾中,沒有路徑文件... – CrazyDev 2011-04-01 07:58:59

+1

使用+ [NSBundle pathForResource:@「csvFile」ofType:@「csv」]獲取csv文件的完整路徑名(作爲NSString)。 – 2011-04-01 08:52:22