2012-09-25 21 views
0

我正在構建一個應用程序,使用它可以上傳包含名字,姓氏和電子郵件3個獨立列的csv文件。用戶界面將有3個文本字段和一個按鈕。當用戶輸入名字或姓氏或電子郵件,然後單擊搜索按鈕時,必須搜索整個文檔並顯示一條提示,說明在該文件中找到該記錄。這是我正在使用的功能,但它只讀取第一行和第一列。請幫助如何讀取csv文件中的單獨字段並與用戶輸入進行比較?

- (void) SearchStudent 

{ 

    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:@"\n"]; 

    NSArray *paColumnsOfRow; 

    NSString *pstrFirstColumn; 



    for(NSString * pstrRow in paRowsOfCSVFile) 

    { 

     paColumnsOfRow= [pstrRow componentsSeparatedByString:@","]; 

     pstrFirstColumn= [paColumnsOfRow objectAtIndex:0]; 

     if([pstrFirstColumn localizedCaseInsensitiveCompare:GWIDText.text] == NSOrderedSame) 

     { 

      UIAlertView *alertingFileName = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Found" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 

      [alertingFileName show]; 

      break; 

     } 

     else 

     { 

      UIAlertView *alertingFileName1 = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Not Found" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 

      [alertingFileName1 show]; 

      break; 

     } 

    } 


} 

回答

0

它看起來像你的其他說法是打破了循環,如果名字不匹配。如果您找到匹配項,您可能需要刪除它並添加一個變量進行跟蹤。只有在符合名稱的情況下才能設置。在for循環後,檢查變量以查看是否有匹配。如果不是,則顯示您的UIAlertView爲「未找到」。

+0

噢亞...我其實沒有別的塊本身試過...但它仍然只是檢查第一行第一列 – dcprog

+0

是什麼\ [paRowsOfCSVFile count \]等於?如果它只有1,並且您的文件有多行,那麼您是否需要在「\ r」而不是「\ n」之間分割? – stevekohls

+0

我使用了\ r ...仍然不工作 – dcprog

0

夫婦的提示:

  1. 你檢查只有一列。

    if([pstrFirstColumn localizedCaseInsensitiveCompare:GWIDText.text] == NSOrderedSame) 
    

做同樣與其他兩列。然後你將解決你的第一個問題,只檢查一列。

  1. 看起來像行終止符不正確。根據創建csv文件的平臺,它可能有不同的行結束符。我建議以記事本++等文本編輯器爲例,查看隱藏的代碼來找出你的行結束符。然後使用終結符來拆分行。請確保你能獲得超過1行(只輸出行變量。
+0

檢查多行?我試過\ n和\ r終止...我使用正常的nodepad創建csv文件 – dcprog

相關問題