0

我正在使用这段代码,但是在分析时,它告诉我在response_error,request_response变量中有很多内存泄漏。

我尝试了几个地方来放置release函数中使用的每个变量的代码,但它也不断崩溃,有和没有错误消息。(最常见的是EXC_BAD_ACCESS它指向内存访问错误)

我认为这可能是NSURLConnection sendSynchronousRequest方法的问题,但我不确定。

有人可以给我一个建议或release在此代码的正确位置放置块吗?

谢谢

NSString *request_url = [NSString stringWithFormat:@"http://www.server.com/api/arg1/%@/arg2/%@/arg3/%@",self._api_key,self._device_id,self._token];
NSURL *requestURL = [NSURL URLWithString:request_url];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:requestURL];
NSError *response_error = [[NSError alloc] init];
NSHTTPURLResponse *_response = [[NSHTTPURLResponse alloc] init];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&response_error];
NSString *str_response = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
return [[str_response JSONValue] valueForKey:@"pairing"];

变量定义如下

@interface MyClass : NSObject {
  NSString *_device_id;
  NSString *_token;
  NSString *_api_key;
}
@property (nonatomic,retain) NSString *_device_id;
@property (nonatomic,retain) NSString *_api_key;
@property (nonatomic,retain) NSString *_token;
4

2 回答 2

3

您正在泄漏_responeresponse_error不必要地分配它们。您正在传递一个指向您的指针的指针,该指针指向一个方法,该方法只会更改创建泄漏的指针。你还需要自动释放str_response

NSError *response_error = nil; //Do not alloc/init
NSHTTPURLResponse *_response = nil; //Do not alloc/init
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&_response error:&response_error];
NSString *str_response = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding] autorelease];
return [[str_response JSONValue] valueForKey:@"pairing"];
于 2011-08-01T14:29:43.343 回答
0

如果您正在调用 alloc/init 而不是调用 release 或 autorelease,那么您很可能会泄漏内存。

于 2011-08-01T14:26:44.323 回答