Question

I'm using ASIHTTPRequest library and I want to be sure if I use it in a good way from the memory management point of view. I create:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:someUrl];

I guess that according to the naming convention I don't have to retain request object, right? but when I look at the code of requestWithURL:someUrl method I can see:

+ (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
}

so the returned object is autoreleased. Shouldn't I retain it in my code?

Was it helpful?

Solution

In general no - as it is autoreleased, its retained by the autorelease pool and that will release it when it goes out of scope. However, you can retain and then release it if you are in a situation where you need the extra security that provides.

OTHER TIPS

If you use autorelease object within a method, you should not retain, so this is okay:

- (void) myMethodDoRequest
{
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:someUrl];
    // use request within this scope only
}

If you want to store the autorelease object in ivar, you have to retain to expand the lifecycle of the object, and latter release to avoid leak:

@interface MyClass
{
    ASIFormDataRequest *request;
}

and

- (void) myMethodStoreRequest
{
    [request release];
    request = [[ASIFormDataRequest requestWithURL:someUrl] retain];
}

- (void) dealloc
{
    [request release];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top