我已经建立了一个nsurl从http获取数据。当我运行仪器时,它说我有一个泄漏的NSFNetwork对象。
我如何在(Void) theConnection中发布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];
}
发布于 2009-12-09 15:22:32
我终于找到了答案。
以上代码中的错误(顺便说一下,它是来自SDK文档的接近精确的示例)不是内存管理代码中的错误。自动发布是一种选择,手动发布是另一种选择。无论您如何处理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。
问题似乎是这个- the SDK缓存iPhone上的请求和回复。即使您的NSMutableURLRequest cachePolicy设置为不从缓存加载应答,也是如此。
愚蠢的是,默认情况下,它似乎缓存了大量数据。我正在传输大量数据(分裂成多个连接),并开始收到内存警告,最后我的应用程序死了。
我们需要的文档在NSURLCache (而不是NSURLConnection)中,它们声明:
NSURLCache通过将NSURLRequest对象映射到NSCachedURLResponse对象来实现对URL请求响应的缓存。它是内存和磁盘上缓存的组合. 提供了操作每个这些缓存的大小以及控制磁盘上用于持久存储缓存数据的路径的方法。
这三行的效果完全是对缓存进行核弹。在将它们添加到我的应用程序(GPS测井)之后,我的#living计数保持稳定。
发布于 2011-07-24 14:32:14
你好,您测试过这个委托方法吗?
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
您可以更精确地管理缓存。
“重置”NSURLCache *sharedCache会在代码的其他部分引起问题吗?
发布于 2009-08-28 08:21:06
这是一个常见的问题,通过对象自动释放的魔力来解决。在您的代码中,如下所示:
NSURLConnection *theConnection = [[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];
通过这种方式,该对象将自动添加到“自动释放池”,并在下一个运行循环开始时不再引用该对象。
希望这有帮助
编辑:,我不明白为什么您需要在receivedData变量上调用-retain。
https://stackoverflow.com/questions/1345663
复制相似问题