2010-06-09 64 views
0
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error]; 

if(results == nil){ 
    NSLog(@"No results found"); 
    searchObj = nil; 
}else{ 
    if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0) { 
     NSLog(@"results %@", [[results objectAtIndex:0] name]); 
     searchObj = [results objectAtIndex:0]; 
    }else { 
     NSLog(@"No results found"); 
     searchObj = nil; 
    }  
} 

上面的代碼將用戶輸入的數據與從數據庫中提取的數據進行比較。如果我輸入數據庫中的數據;有用。但是如果我輸入完整的亂碼,它將返回下面的錯誤,而不是「找不到結果」。iPhone:比較錯誤和錯誤處理混淆

*** WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSRangeException> *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 

結果數組爲空應在上面的代碼檢查過程中考慮,否?

回答

3

您在下面的代碼行可能拋出異常:

if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0)

如果數組初始化並具有零個元素,你會通過零檢查,但你會拋出一個嘗試訪問數組內部的任何對象時出現異常。可以返回空數組。您應該使用NSArray的count方法而不是檢查數組是否爲零。

我建議你在objc_exception_throw和[NSException raise]上設置一個斷點,以幫助你調試你的應用程序。然後在gdb中運行回溯來查看拋出異常的位置,以進一步診斷真正的問題。

克里斯·漢森對如何完成上述這些位於here

+0

使用,如果([結果計數] == 0)完美工作一個偉大的書面記錄。感謝您的幫助和斷點資源。 – 2010-06-09 19:02:15