user1242094
user1242094

Reputation: 107

Objective-C - unidentified Error in for Loop

the following code attempts to search for a String given by a cell.textlabel.text in a CSV-File

- (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];
        }

    }


}

Working quite a bit with csv-files in my current project I'm pretty sure this should work, but somehow the app always crashes when the function is called.

Through a whole bunch of testing I'm pretty sure that the problem is in the following lines:

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

The program works with these two lines commented out, but doesnt implement the desired function ;) I have no clue what the problem might be?

The Error is a SIGABRT in "main".

Thanks in advance everybody.

Upvotes: 0

Views: 111

Answers (1)

Ashwin Kumar
Ashwin Kumar

Reputation: 622

Might crash when your currentArray has elements less than 3 and you are referring index 3. So in that case your finding for an index which is out of reach.

So better approach would be

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

Upvotes: 1

Related Questions