connection release method in connectionDidFinishLoading, causes error

点点圈 提交于 2019-12-25 07:29:30

问题


testing request and getting the response example in official apple developer site.

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

using [connection release] method in connectionDidFinishLoading, causes error :Should've been invalidated - EXC_BAD_ACCESS

if I comment line [connection release] method; everything seems working but Im afraid there is memory leak occurs because of non existent release of connection.

what may cause or how can I avoid this problem ?

@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];
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [dataStore appendData:data]; }
- (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];
  }

回答1:


You create your connection using a factory method. Only if you use alloc/init, new, copy, or retain should you use release. In this case, the system will take care of releasing the object for you.

Better yet, use ARC.



来源:https://stackoverflow.com/questions/18559573/connection-release-method-in-connectiondidfinishloading-causes-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!