在官方苹果开发者网站上测试请求并获取响应示例。
在connectionDidFinishLoading中使用[connection release]方法, 导致错误:应该是否已失效 - 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 *)连接didReceiveData:(NSData *)数据 { [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];
}
答案 0 :(得分:0)
使用工厂方法创建连接。仅当您使用alloc/init
,new
,copy
或retain
时,才应使用release
。在这种情况下,系统将负责为您释放对象。
更好的是,使用ARC。