gpt4 book ai didi

ios - NSURlConnection 取消导致内存泄漏

转载 作者:行者123 更新时间:2023-11-28 20:44:53 25 4
gpt4 key购买 nike

这是一个非常奇怪的错误。

如果下载完成,我使用代码通过 NSURLConnection 下载文件,我没有泄漏。但是如果我取消下载,我有 1Mo 内存不会释放。我已经用仪器进行了测试,发现造成这种泄漏的方法是

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

真的很奇怪

这是我创建、管理和取消下载的代码

注意:此下载是核心数据托管对象的一部分,但我认为核心数据不对我的泄漏负责。

- (void)loadURL:(NSURL *)url
{

if (currentLoadingDatas) { // just bool for prevent multiple download

return;
}
currentLoadingDatas = YES;


NSURLRequest *request = [[NSURLRequest alloc]
initWithURL: url
cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval: 60
];
connectionDatas = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];

}

#pragma mark NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

if (!self.transientData) {

self.transientData = [[NSMutableData alloc] init];
}
[self.transientData setLength:0];



}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.transientData appendData:data];


}



- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

[self willChangeValueForKey:@"datas"];
[self setValue:self.transientData forKey:@"datas"];
[self didChangeValueForKey:@"datas"];

[self.transientData release];


NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];



}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {


NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];


}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}

-(void)cancelDownload
{
[self.connectionDatas cancel];


}

// fired by coreData
-(void)willTurnIntoFault
{


self.transientData = nil;
[self cancelDownload];

[super willTurnIntoFault];
}

// fired by coreData
-(void)didTurnIntoFault
{

[connectionDatas release];

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];

[self.transientData release];
[super didTurnIntoFault];
}

你能帮我找出问题所在吗?

非常感谢。

最佳答案

self.transientData 属性是如何声明的?
因为你初始化: self.transientData = [[NSMutableData alloc] init]; 并且如果属性设置为保留值,你将需要释放它两次。

如果是这样,设置属性使用:self.transientData = [[[NSMutableData alloc] init] autorelease]; 或者简单地 [NSMutableData data];.< br/>其余的对我来说似乎没问题。

关于ios - NSURlConnection 取消导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com