【问题标题】:connection release method in connectionDidFinishLoading, causes errorconnectionDidFinishLoading 中的连接释放方法,导致错误
【发布时间】:2013-09-04 18:10:30
【问题描述】:

在苹果官方开发者网站中测试请求并获取响应示例。

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


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

【问题讨论】:

  • 如何创建NSURLConnection 实例?
  • 问题随着 NSURLConnection 实例的创建而更新。使用简单 CustomNSObject 的单例实例。谢谢。

标签: nsurlconnection exc-bad-access nsurlconnectiondelegate


【解决方案1】:

您使用工厂方法创建连接。只有当您使用alloc/initnewcopyretain 时,您才应该使用release。在这种情况下,系统会为您释放该对象。

更好的是,使用 ARC。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多