I’m new in programming obj-c. So, when shall i release the defined objects?
Do i have to release urlRequest, response, data and content?
- (NSString*)getContentFromUrl:(NSURL*)url {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setHTTPMethod:@"GET"];
[urlRequest setURL:url];
NSHTTPURLResponse *response = NULL;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:nil];
NSString *content = NULL;
if ([response statusCode] >= 200) {
content = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
}
[content autorelease];
return content;
}
You have to release
urlRequestonly.response,dataare created already as autoreleased objects andcontentreceives autorelease message before return (I’d suggest changing last two lines with justreturn [content autorelease]).It’s also more common to initialize object pointers to
nilrather thanNULL.Cocoa has a convention if you call
alloc,copy,retainornewon any of objects while initializing or reassigning them you have toreleasethem unless they receiveautoreleasemessage after creation.You can see from your code that only
urlRequestandcontentvariables are created usingallocmethod, hence they have to be [auto]released.update minding the comments
If you have
urlRequestas an instance variable the previously initiated variable can shadow the ivar and you may get into various troubles (likeEXC_BAD_ACCESS). You better pick a different name for your local variable.