objective-c – NSURLConnection泄漏?
我已经设置了一个nsurl,它从http获取数据.
当我运行仪器,它说我有一个泄漏NSFNetwork对象. 并且如何释放(void)ButtonClicked中的连接?还是稍后再发布? - (void)ButtonClicked { NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:KmlUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0f]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { // receivedData is declared as a method instance elsewhere NSMutableData *receivedData = [[NSMutableData data] retain]; [self setKMLdata:receivedData]; } else { // inform the user that the download could not be made } } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // append the new data to the receivedData // receivedData is declared as a method instance elsewhere [KMLdata appendData:data]; NSLog(@"didReceiveData"); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // release the connection,and the data object [connection release]; [KMLdata release]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // release the connection,and the data object [connection release]; // receivedData is declared as a method instance elsewhere [KMLdata release]; } 解决方法
我终于找到了答案.
上述代码中的错误(顺便说一下,来自SDK docs的近似精确的样本)不在内存管理代码中.自动释放是一种选择,手动释放是另一种选择.无论如何处理您的NSURLConnection对象,都会使用NSURLConnection获得泄漏. 首先,这里是解决方案.只需将这3行代码直接复制到connectionDidFinishLoading,didFailWithError和其他任何地方释放NSURLConnection对象. NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]; [NSURLCache setSharedURLCache:sharedCache]; [sharedCache release]; 授予http://forums.macrumors.com/showthread.php?t=573253的mpramodjain代码. 问题似乎是这样的 – SDK缓存iPhone上的请求和回复.即使您的NSMutableURLRequest cachePolicy设置为不从缓存加载回复似乎. 愚蠢的是,默认情况下它似乎缓存了很多数据.我传输了大量数据(分为多个连接),并开始获取内存警告,最后我的应用程序死了. 我们需要的文档是NSURLCache(不是NSURLConnection),它们说明:
这三行具有完全禁止缓存的效果.添加到我的应用程序(GPS Log)后,我的#living对象计数保持稳定. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |