Objective C: Potential Memory Leak in code
I ran the 'Analyze' on my code and the result shows a potential memory leak on the following part of my code
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//Potential memory leak in code below
[[NSURLConnection alloc] initWithRequest:request delegate:self];
I am not sure how to stop this leak. I tried to add a 'autorelease' to the back but that caused a crash. Any advise on this开发者_运维技巧?
EDIT:
Screenshot of the leak message
Release the connection object on success or failure. It needs to stay alive till then. So put a release in both connection:didFailWithError:
and connectionDidFinishLoading:
delegate methods. Only one will get called. So retain-release will balance out.
Your call to alloc on NSURLConnection is returning an object with a reference count of 1. Your code should be as following:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start]; // This is optional. It should begin the request after you alloc it
After you are done with the object, you need to explicitly call:
[connection release];
Use the static method
[NSURLConnection connectionWithRequest:request delegate:self];
instead of
[[NSURLConnection alloc] initWithRequest:request delegate:self];
of course there is NO need to release the connection object in it's delegate methods.
Or if you use the second method, release the NSURLConnection object in both delegate methods:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
and can ignore the memory leak warning message.
精彩评论