0

我正在使用此代碼,但在分析時,它告訴我在response_error,request_response變量內有許多內存泄漏。HTTP請求內存泄漏

我嘗試了幾個地方把每個變量的release代碼用在函數中,但是它也一直崩潰,並且沒有錯誤信息。 (通常是EXC_BAD_ACCESS其中指向內存訪問錯誤)

我認爲這可能是NSURLConnection sendSynchronousRequest方法的問題,但我不確定。

有人可以給我一個建議或地方release塊在這個代碼的正確位置?

感謝

NSString *request_url = [NSString stringWithFormat:@"http://www.server.com/api/arg1/%@/arg2/%@/arg3/%@",self._api_key,self._device_id,self._token]; 
NSURL *requestURL = [NSURL URLWithString:request_url]; 
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:requestURL]; 
NSError *response_error = [[NSError alloc] init]; 
NSHTTPURLResponse *_response = [[NSHTTPURLResponse alloc] init]; 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&response_error]; 
NSString *str_response = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
return [[str_response JSONValue] valueForKey:@"pairing"]; 

其中變量像

@interface MyClass : NSObject { 
    NSString *_device_id; 
    NSString *_token; 
    NSString *_api_key; 
} 
@property (nonatomic,retain) NSString *_device_id; 
@property (nonatomic,retain) NSString *_api_key; 
@property (nonatomic,retain) NSString *_token; 

回答

3

您正在泄漏_responeresponse_error不必要地分配它們。你正在傳遞一個指向你的指針的指針,這個指針只會改變創建泄漏的指針。你也需要自動釋放str_response

NSError *response_error = nil; //Do not alloc/init 
NSHTTPURLResponse *_response = nil; //Do not alloc/init 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&response_error]; 
NSString *str_response = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding] autorelease]; 
return [[str_response JSONValue] valueForKey:@"pairing"]; 
+0

很棒,就像一個魅力:) –

0

定義如果您呼叫分配/初始化,然後沒有要求釋放或自動釋放,賠率是你會泄漏內存。

+0

但問題是在哪裏以及如何發生的釋放塊,因爲'NSAutorelease'塊用'返回之前drain'權利沒有得到正確處理泄漏,我手寫釋放造成內存訪問錯誤。 –