gpt4 book ai didi

iphone - NSMutableData 的内存泄漏

转载 作者:行者123 更新时间:2023-12-03 20:23:06 34 4
gpt4 key购买 nike

我有一个用于连接 httprequests 的类。我收到“NSMutableData”的内存泄漏,尽管我在连接对象的“didFailWithError”和“connectionDidFinishLoading”中释放它:

- (BOOL)startRequestForURL:(NSURL*)url {

[url retain];


NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
// cache & policy stuff here
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPShouldHandleCookies:YES];
NSURLConnection* connectionResponse = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
if (!connectionResponse)
{
// handle error
return NO;
} else {
receivedData = [[NSMutableData data] retain]; // memory leak here!!!
}

[url release];

[urlRequest release];


return YES;}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
UIAlertView *alert =
[[[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Connection problem", nil)
message:NSLocalizedString(@"A connection problem detected. Please check your internet connection and try again.",nil)

delegate:self
cancelButtonTitle:NSLocalizedString(@"OK", nil)
otherButtonTitles:nil, nil]
autorelease];
[alert show];

[connectionDelegate performSelector:failedAction withObject:error];
[receivedData release];}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[connectionDelegate performSelector:succeededAction withObject:receivedData];
[receivedData release];}

最佳答案

静态分析器会将此称为泄漏,因为您无法保证具有 release 功能的任何一个方法实际上都会被调用。

如果您将 receivedData 设置为保留属性,并且执行以下操作

self.receivedData = [NSMutableData data];

然后在你的 dealloc 中(还有 didFail 和 didFinish,而不是释放):

self.receivedData = nil;

你会没事的。

正如 jbat100 所指出的,如果 !connectionResponse,您还会泄漏 url 和 urlRequest,除非您从问题中省略了此代码

关于iphone - NSMutableData 的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7659711/

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