I have followed the instruction from Using NSURLConnection and sometimes (very very seldom) my project crashes in method.
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[myNSMutableData release];
}
It crashes when i try to release my NSMutableData
.
I want to know why it crashes!
Some code I use:
- (void) start
{
while (1)
{
NSString *stringURL = @"http://www.iwheelbuy.com/get.php?sex=1";
NSURL *url = [NSURL URLWithString:stringURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
getData = [[NSMutableData data] retain];
break;
}
else
{
NSLog(@"no start connection");
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if ([connection.originalRequest.URL.absoluteString rangeOfString:@"get.php"].location != NSNotFound)
{
[getData setLength:0];
}
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if ([connection.originalRequest.URL.absoluteString rangeOfString:@"get.php"].location != NSNotFound)
{
[connection release];
[getData release];
}
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if ([connection.originalRequest.URL.absoluteString rangeOfString:@"get.php"].location != NSNotFound)
{
[connection release];
NSString *html = [[NSString alloc] initWithData:getData encoding:NSASCIIStringEncoding];
[getData release];
if ([html rangeOfString:@"id1="].location != NSNotFound && [html rangeOfString:@"id2="].location != NSNotFound)
{
NSLog(@"everything is OKAY");
[html release];
}
else
{
[html release];
[self start];
}
}
}
You need to release
getData
instead ofmyNSMutableData
.Your code is performing asynchronous calls. Each time you call your start method you create new instance of NSURLConnection object but you have only one object (getData) for data. Considering some how there are two simultaneous calls and when first one failed it released your connection and getData object and when the second one fails it releases your connection object successfully but your getData object is already released in previous fail call causing your code to crash.
To fix this always set your objects to nil after you release them and perform nil check where necessary.