Objective-C - for循环中的未识别错​​误

时间:2012-08-31 08:57:50

标签: iphone objective-c ios xcode

以下代码尝试在CSV文件中搜索由cell.textlabel.text提供的字符串

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//create singleton instance
Globals *myGlobals = [Globals sharedGlobals];

//get searchstring form cell
NSString *stringToFind = [self.tableView cellForRowAtIndexPath:indexPath].textLabel.text;

//get Path of csv and write data in string:allLines
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ITILcsv" ofType:@"txt"];
if(filePath){

    NSString *wholeCSV = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSArray *allLines = [wholeCSV componentsSeparatedByString:@"\n"];
    //declaration
    NSArray *currentArray = nil;
    NSString *currentSearchString = nil;

//look for searchstring in 4th line of csv, if found write whole line to a singleton-variable
    for (int i=0 ; i < [allLines count]; i++){

        currentArray = [[allLines objectAtIndex:i] componentsSeparatedByString:@";"];
        currentSearchString = [currentArray objectAtIndex:3];

        if ([stringToFind isEqualToString:currentSearchString]){

            [myGlobals setCurrentLine:currentArray];
        }

    }


}

在我当前的项目中使用csv-files工作很多我很确定这应该可以工作,但是当调用该函数时,应用程序总会崩溃。

通过一系列测试,我很确定问题出在以下几行:

 currentArray = [[allLines objectAtIndex:i] componentsSeparatedByString:@";"];
        currentSearchString = [currentArray objectAtIndex:3];

该程序使用这两行注释掉,但没有实现所需的功能;) 我不知道问题可能是什么?

错误是“主要”中的SIGABRT。

先谢谢大家。

1 个答案:

答案 0 :(得分:1)

currentArray 的元素小于3 并且引用索引3 时,可能会崩溃。因此,在这种情况下,您找到的指数是遥不可及的。

更好的方法是

for (int i=0 ; i < [allLines count]; i++)
{
    currentArray = [[allLines objectAtIndex:i] componentsSeparatedByString:@";"];

    // check and then pick
    if ([currentArray count] > 3)
    {
        currentSearchString = [currentArray objectAtIndex:3];

        if ([stringToFind isEqualToString:currentSearchString])
        {
            [myGlobals setCurrentLine:currentArray];
        }
    }
}
相关问题