简体   繁体   中英

How to check contents of a column in a CSV file?

I am developing a small app where the user uploads a csv file to the document folder in the app through iTunes. I am using the following code, but it checks only the first column in first row. Its not checking the second rows column. My csv file contains 2 rows and 4 columns each. First column is a number. The user will type this number in a text box and click a button to check whether the number is in csv file. The following function is the one I am using

-(void)CheckEntry //this function checks the example.csv file
{
    NSArray *DocumentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *DocumentDirectory = [DocumentPath objectAtIndex:0];

    NSString *FullPath = [DocumentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"example.csv"]];

    NSString * pstrCSVFile= [NSString stringWithContentsOfFile:FullPath encoding:NSASCIIStringEncoding error:NULL];

    NSArray * paRowsOfCSVFile= [pstrCSVFile componentsSeparatedByString:@"\r\n"];

    NSArray *paColumnsOfRow;
    NSString *pstrFirstColumn;
    for(NSString * pstrRow in paRowsOfCSVFile)
    {
        paColumnsOfRow= [pstrRow componentsSeparatedByString:@","];
        pstrFirstColumn= [paColumnsOfRow objectAtIndex:0];

        if([pstrFirstColumn localizedCaseInsensitiveCompare:GWIDText.text] == NSOrderedSame)
        {
            NSString *msg = [NSString stringWithFormat:@"The record was found"];
            UIAlertView *alertingFileName = [[UIAlertView alloc]initWithTitle:msg message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertingFileName show];
        }
        else
        {
            NSString *msg = [NSString stringWithFormat:@"Not Found"];
            UIAlertView *alertingFileName = [[UIAlertView alloc]initWithTitle:msg message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertingFileName show];
        }
    }

}

You are trying to show an alert view inside a loop. So you end up trying to show as many alert views as there are rows. That is unlikely what you want. Your requirement is unclear. Do you want to check all columns of all rows, just the first column of all rows, or simply find the first match and stop?

Create a BOOL variable just before the loop. Something like BOOL found = NO; . Then in the loop, set the variable to YES when you find a match. Then, after the loop, show the proper alert based on the found variable. The exact solution really depends on your true intent here.

尝试使用componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet],而不是componentsSeparatedByString :,看看是否有帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM