5

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?

Jakub
  • 3,129
  • 8
  • 44
  • 63

2 Answers2

5

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];
}
Ivan Marinov
  • 2,737
  • 1
  • 25
  • 17
3

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.

Andiih
  • 12,285
  • 10
  • 57
  • 88
  • But then, if I don't retain the object it is possible that the autorelease pool will release it and I will end up with an invalid object, right? – Jakub Jun 09 '10 at 14:28
  • It depends on your architecture, but I don't think so (I've not had any errors myself, put it that way) however, if you have scope to retain then release you will not do any harm! – Andiih Jun 09 '10 at 17:30