开发者

HTTP Request Memory leaks

I'm using this code, but when profiling, it tells me I have a many memory leaks within response_error, request and _response variables.

I tried several places to put a release code of each variable used in function, but it keeps crashing with and without error message too. (most often it is EXC_BAD_ACCESS which points to memory access error)

I think it could be problem of NSURLConnection sendSynchronousRequest method, but I'm not sure.

Can somebody please give me an advice or place release blocks in right place of this code?

Thanks

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];
N开发者_开发技巧SError *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"];

where variables are defined like

@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;


You are leaking _respone and response_error by needlessly allocating them. You are passing a pointer to your pointer to a method that will just change the pointer creating a leak. Also you need to autorelease 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"];


If you are calling alloc/init and then not calling release or autorelease, odds are you are going to leak memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜