开发者

When shall i release these objects in objective-c?

开发者 https://www.devze.com 2023-04-12 12:06 出处:网络
开发者_JAVA技巧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?

开发者_JAVA技巧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 urlRequest only. response, data are created already as autoreleased objects and content receives autorelease message before return (I'd suggest changing last two lines with just return [content autorelease]).

It's also more common to initialize object pointers to nil rather than NULL.

Cocoa has a convention if you call alloc, copy, retain or new on any of objects while initializing or reassigning them you have to release them unless they receive autorelease message after creation.

You can see from your code that only urlRequest and content variables are created using alloc method, hence they have to be [auto]released.

update minding the comments

If you have urlRequest as an instance variable the previously initiated variable can shadow the ivar and you may get into various troubles (like EXC_BAD_ACCESS). You better pick a different name for your local variable.

0

精彩评论

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

关注公众号