使用componentsSeperatedByString的obj-c问题设置数组

时间:2010-04-10 16:13:52

标签: iphone objective-c arrays nsdata

我有一个大约有2000行的数据源,如下所示:

6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,美国,AKP,PAKP,68.1336,-151.743,2103,-9,A

我感兴趣的是这个字符串的第6部分,所以我想把它变成一个数组,然后我想检查第6节[5]是否出现了字符串“PAKP”

代码:

NSBundle *bundle = [NSBundle mainBundle];
    NSString *airportsPath = [bundle pathForResource:@"airports" ofType:@"dat"];
    NSData *data = [NSData dataWithContentsOfFile:airportsPath];

    NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];

NSArray *dataArray = [dataString componentsSeparatedByString:@"\n"];
    NSRange locationOfAirport;
    NSString *workingString = [[NSString alloc]initWithFormat:@""];
    NSString *searchedAirport = [[NSString alloc]initWithFormat:@""];
    NSString *airportData = [[NSString alloc]initWithFormat:@""];

    int d;

    for (d=0; d < [dataArray count]; d=d+1) {
        workingString = [dataArray objectAtIndex:d];
            testTextBox = workingString; //works correctly
        NSArray *workingArray = [workingString componentsSeparatedByString:@","];
            testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
            testTextBox3 = [workingArray objectAtIndex:1] //throws exception index beyond bounds
        locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:@"PAKP"];


    }

问题是当workingArray填充时,它只填充一个对象(字符串的第一个组件是“6712”。如果我有它显示workString,它会正确显示整个字符串,但是对于某些原因是,它没有正确地使用逗号制作数组。

我在不使用数据文件的情况下尝试了它并且工作正常,因此问题来自于我如何导入数据。

想法?

2 个答案:

答案 0 :(得分:2)

您的代码有效。您应该使用调试器运行它以查看发生了什么。猜测,您的输入数据不是您认为的 - 可能是不同的编码或不同的行结尾。

见样本:

NSString *dataString = @"6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A";
NSArray *dataArray = [dataString componentsSeparatedByString:@"\n"];
for (NSString *workingString in dataArray) {
    NSString *testTextBox = workingString; //works correctly
NSArray *workingArray = [workingString componentsSeparatedByString:@","];
    NSString *testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
    NSString *testTextBox3 = [workingArray objectAtIndex:1]; //throws exception index beyond bounds
NSRange locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:@"PAKP"];
}

答案 1 :(得分:0)

数据中存在一些问题导致错误。