在connectionDidFinishLoading连接释放的方法,会导致错误(connectio

2019-10-30 02:09发布

测试要求,并得到官方的苹果开发者网站的响应例子。

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

Answer 1:

创建使用工厂方法的连接。 只有当你使用alloc/initnewcopy ,或retain你应该使用release 。 在这种情况下,系统会释放对象对你的照顾。

更重要的是,使用ARC。



文章来源: connection release method in connectionDidFinishLoading, causes error