【发布时间】:2011-03-05 07:39:04
【问题描述】:
您好,另一个关于泄漏和 NSURLConnection 的愚蠢问题。我如何释放它?如果我通过以下两种方法发布就足够了吗?
(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error (void)connectionDidFinishLoading:(NSURLConnection *)connection因为在仪器中它向我显示了我将连接分配为泄漏源的线路。
(EDIT1:好的,我不明白。在以下代码之后,我的 urlConnection 的保留计数为 2。WTF?)
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];这是仪器指向我的线。
EDIT2:这是一些代码:
我在这里创建连接
- (void) makeRequest { //NSString *urlEncodedAddress = [self.company.street stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; NSString *urlString = [[NSString alloc] initWithFormat: @"http://maps.google.com/maps/api/geocode/xml?latlng=%f,%f&sensor=false", bestEffort.coordinate.latitude,bestEffort.coordinate.longitude]; debugLog(@"%@",urlString); NSURL *url = [[NSURL alloc] initWithString: urlString]; [urlString 发布]; NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL: url]; [网址发布]; NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self]; debugLog(@"connection created %@ rc %i", urlConnection, urlConnection.retainCount); [url请求发布]; 连接 = urlConnection; }这里放出来
-(void)connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error { debugLog(@"连接错误:%@", error.localizedDescription); //[activityIndicator setHidden:YES]; debugLog(@"连接将被释放,否则 %@ %i", _connection, [_connection retainCount]); [连接释放]; 连接=无; [网络数据发布]; 网络数据=无; 如果(!取消) [委托 rgc_failedWithError: self : error]; isWorking = FALSE; }或者这里
-(void)connectionDidFinishLoading:(NSURLConnection *)_connection { debugLog(@"连接将被释放(否则)%@ %i", _connection, [_connection retainCount]); [连接释放]; 连接=无; debugLog(@"DONE. Received Bytes: %d", [webData length]); //NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; //debugLog(@"%@",theXML); //[XML 发布]; ...... ...... }EDIT3:通过不关心它是否泄漏来解决问题!简单!
【问题讨论】:
-
如果您发布一些源代码,那么为您提供正确答案会容易得多
-
好吧,我建立了一个连接,它马上就有了 rc: 2 (!)。在释放错误或成功事件处理程序之前,它仍然有 2 个 rc。
-
顺便说一句,如果我在 alloc 之后执行额外的发布,它会在 connectionDidFinishLoading 中给我一个 EXC_BAD_ACCESS :)
-
不要担心保留计数。底层框架会根据需要保留连接,并适当释放。它崩溃是因为当你添加一个额外的版本时,它基本上已经发布了 3 次,而它应该是 2 次。
-
好吧,如果仪器不会将其报告为泄漏,我也不会担心保留计数。这只是对额外版本的快速测试。
标签: iphone objective-c memory-management memory-leaks nsurlconnection