View Full Version : How can I get the content of an URL without having memory leaks?

Jan 5, 2009, 04:03 AM
Hi all,

For my iPhone's project, I need to retrieve some URL's contents, but I'm facing memory leaks when using [NSString stringWithContentsOfURL:] (I've submitted the bug to Apple, waiting for their answer).

I can not imagine that I'm the only one needing to get URL's content.

So, I'm wondering how all other developers are doing to avoid these leaks.

Please help me.

Thanks in advance.

Best regards,

Jan 5, 2009, 04:30 AM
Use NSURLConnection (http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/doc/uid/20001697). Make sure you use the async methods/callbacks as sendSynchronousRequest:returningResponse:error: leaks which is most likely the root cause of the leak you are seeing.

Jan 5, 2009, 07:36 AM
Thanks for your quick answer.

I tried to use [NSURLConnection connectionWithRequest:] to get content of an URL, but Instrument still detects a memory leak in CFNetwork.
The leaked Object is "GeneralBloc-3584".

Maybe I did a mistake.

Do someone has sample code without any memory leak for this issue?

Jan 5, 2009, 07:39 AM
Why don't you post your code with all the async handler callbacks so we can see what you might be doing wrong?

Jan 5, 2009, 08:11 AM
OK, why not.


#import "TestConnectionAppDelegate.h"

@implementation TestConnectionAppDelegate

@synthesize window;
@synthesize responseData=_responseData;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window makeKeyAndVisible];

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.puzzlemaniak.com"]];

[NSURLConnection connectionWithRequest:req delegate:self];

- (void)dealloc {
[window release];
[super dealloc];

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

if (!_responseData) {
[self setResponseData:[NSMutableData data]];

[_responseData appendData:data];

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)URLresponse {

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)URLresponse;

if (![httpResponse isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(@"Unknown response type: %@", URLresponse);

_responseStatusCode = [httpResponse statusCode];


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

NSString* res=[[[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding] autorelease];


TestConnectionAppDelegate .h:

#import <UIKit/UIKit.h>

@interface TestConnectionAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
NSURLConnection *_connection;
NSMutableData *_responseData;
NSMutableString *_xmlChars;

NSInteger _responseStatusCode;

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (retain) NSMutableData *responseData;