释放NSMutableData时NSURLConnection崩溃

我遵循使用NSURLConnection的指令,有时(很less)我的项目崩溃的方法。

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [connection release]; [myNSMutableData release]; } 

它崩溃时,我试图释放我的NSMutableData 。 我想知道它为什么崩溃!

我使用的一些代码:

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

您的代码正在执行asynchronous调用。 每次调用start方法时,都会创buildNSURLConnection对象的新实例,但只有一个对象(getData)用于数据。 考虑一些如何有两个同时调用,当第一个失败它释放你的连接和getData对象,当第二个失败它释放你的连接对象成功,但你的getData对象已经释放在以前的失败调用导致您的代码崩溃。

要解决这个问题,总是把你的对象设置为零,然后释放它们,并在必要时执行零检查。

您需要释放getData而不是myNSMutableData