0

測試請求並在官方Apple開發人員網站中獲取響應示例。connectionDidFinishLoading中的連接釋放方法會導致錯誤

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

使用[連接釋放]方​​法connectionDidFinishLoading, 導致錯誤:應該已經失效 - EXC_BAD_ACCESS

如果我評論線[連接釋放]的方法;一切似乎工作,但 恐怕有內存泄漏發生,因爲不存在的連接釋放。

什麼可能導致或我該如何避免此問題?

@imlementation test 
NSMutableData *dataStore=nil; 

//example usage: 
//[self registerToServer:@"http://testserver.com/registeruser.ashx" withUserName:@"john doe" withPassword:@"123456"]; 

-(void)registerToServer:(NSString*)urlstr withUserName:(NSString*) 
ausername withPassword:(NSString*)apassword 
{ 
    NSURL *url=[NSURL URLWithString:urlstr]; 
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:3.0f]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:ausername forHTTPHeaderField:@"pass"]; 
[request setValue:apassword forHTTPHeaderField:@"username"]; 
NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self]; 
[connection start]; 

if(connection) 
    dataStore=[[NSMutableData data]retain]; 
} 


- (無效)連接:(NSURLConnection的*)連接didReceiveData:(NSData的*)數據 { [數據存儲區appendData:數據]; }

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
[dataStore setLength:0];} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
NSLog(@"connection failed:%@ %@", 
     [error localizedDescription], 
     [[error userInfo]objectForKey:NSURLErrorFailingURLStringErrorKey]); 

[connection release]; 
[dataStore release]; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
    { 
    //[connection release]; //WELL... I CANT COMMENT OUT THIS LINE! 
    NSString *res=[[NSString alloc]initWithData:dataStore encoding:NSUTF8StringEncoding]; 

    NSLog(@"%@",res); 
[dataStore release]; 
    } 
+0

你如何創建'NSURLConnection'實例? –

+0

用NSURLConnection實例創建更新的問題。 使用簡單的CustomNSObject的單例實例。 謝謝。 –

回答

0

您使用工廠方法創建連接。如果您使用alloc/initnewcopyretain,則應使用release。在這種情況下,系統將負責爲您釋放物體。

更好的是,使用ARC。

相關問題