2011-10-24 41 views
2

我需要,爲什麼我得到想要的NSError分配給一個傳遞給函數時的誤差的第二雙眼睛:NSError EXC_BAD_ACCESS

// Response and Error Objs. 
NSURLResponse *response = nil; 
NSError *requestError = nil; 

// Attempt authentication 
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError]; 

// Error? 
if (requestError != nil) { 
    *error = requestError; // Error happens here 
    return; 
} 
+0

也許有人通過了'nil'?定義在哪裏? –

回答

0

你忘了NSError:

if (requestError != nil) { 
    NSError *error = requestError; // Error happens here 
    return; 
} 

或者何時/何時error被聲明/定義以及將一個錯誤對象指定給另一個對象是什麼?爲什麼不只是:

if (requestError != nil) { 
    NSLog(@"%@", [requestError localizedDescription]); 
    return; 
} 
0

最有可能*error不指向一個有效的指針;樣本不完整,所以我不能肯定地說。也許*error是零。

1

從蘋果公司的Error Handling Programming Guide

Important: Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

在這種情況下,-sendSynchronousRequest:returnResponse:error:返回NSData對象。在繼續處理錯誤之前,您應該檢查是否爲零。

0

您無法在您嘗試使用的表單中使用'錯誤'。你可以在NSURLConnection中訪問錯誤,但不能在它之外。因此你需要在使用它之前定義你的錯誤對象。

0

可以說你有一個方法簽名,接受NSError**

這意味着該方法接受指向指向NSError值的指針的指針。

所以,我懷疑是因爲錯誤是NULL,你基本上要求NULL對象的值是它指向的東西。但是,當然,你不能要求一個NULL對象的信息,這就是它崩潰的原因。

所以,你嘗試設置的*error值之前,你需要檢查error沒有NULL像這樣:

if (error == NULL) { 
    // the function caller has supplied us with a nil as an argument 
    // this indicates the caller does not care about the error 
    return; 
} 

你必須檢查NULL,而不是nil的原因是因爲你檢查內存位置不是可可物體。