Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to retain autoreleased objects?

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?

like image 707
Jakub Avatar asked Jun 09 '10 09:06

Jakub


People also ask

When should you retain release?

The basic premise behind the system is that if you want to hold on to a reference to another object, you need to issue a retain on that object. When you no longer have a use for it, you release it.

What is an Autorelease object?

An autorelease pool is actually a collection of objects that will be released at some point in the future (either at the end of the thread's run loop or at the end of the scope of an autorelease pool). When a pool is drained, all the objects in the pool at that time are sent the release message.

How is Autorelease pool managed?

An autorelease pool stores objects that are sent a release message when the pool itself is drained. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.

What is Autoreleasepool Swift?

Memory management in swift is handled with ARC (= automatic reference counting). This means that active references to objects are counted and objects are released when they aren't referenced anymore.


2 Answers

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];
}
like image 170
Ivan Marinov Avatar answered Oct 17 '22 01:10

Ivan Marinov


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.

like image 35
Andiih Avatar answered Oct 17 '22 00:10

Andiih