Objective C读取csv文件并使用数组

时间:2011-04-01 14:00:18

标签: objective-c arrays xcode csv

我有一个csv文件:

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

我使用以下代码阅读此文件:

NSString *resourceFileName = @"PrenotazioniDb";
NSString *pathToFile =[[NSBundle mainBundle] pathForResource: resourceFileName ofType: @"txt"];
NSError *error;

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

NSString *one = nil, *two = nil, *three = nil, *four = nil; 
while ([scanner scanUpToString:@"#" intoString:&one] && [scanner scanUpToString:@"#" intoString:&two] && [scanner scanUpToString:@"#" intoString:&three] && [scanner scanUpToString:@"#" intoString:&four]{


}

但我想记住数组中的文件,我该怎么办?我应该使用两个数组:一个用于行,一个用于单个字;例如,在我存储的位置的第一个数组中

1#one#two#three#four;

并且在第二个数组中,我在第一个位置“1”存储在第二个“one”中的第三个“两个”分机....

我能做什么?

1 个答案:

答案 0 :(得分:0)

您可以使用componentsSeparatedByString方法。

NSString *list=@"1#one#two#three#four"; 
NSArray *listItems = [list componentsSeparatedByString:@"#"];
NSLog(@"listItems= %@",listItems);

打印:

listItems= (
    1,
    one,
    two,
    three,
    four
)