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.
Frage
testing request and getting the response example in official apple developer site.
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 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];
}
Lösung
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.