当我运行仪器,它说我有一个泄漏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),它们说明:
NSURLCache implements the caching of
responses to URL load requests by
mapping NSURLRequest objects to
NSCachedURLResponse objects. It is a
composite of an in-memory and an
on-disk cache.Methods are provided to manipulate the
sizes of each of these caches as well
as to control the path on disk to use
for persistent storage of cache data.