Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C autorelease memory management

Im trying to understand when to call autorelease, and what this will actually do to my object.

After reading About Memory Management in the Mac Developer Library I understood that when you have a method that acts as a factory method - by creating a new object and returning it - the method has no way of releasing the object before returning it, because this would result in a deallocted object being returned.

Example

- (Test *) createNewTest 
{
    Test *newInstance = [[Test alloc] init];
    [newInstance release];
    return newInstance; // deallocted object returned.
}

Instead I should use autorelease:

The autorelease method, defined by NSObject, marks the receiver for later release

My question is: if the object is to be released later, how do I know when its being released?

- (Test *) createNewTest 
{
    Test *newInstance = [[test alloc] init];
    [newInstance autorelease];
    return newInstance;
}

- (void) runIt
{
    Test *myInstance = [self createNewTest];
    // when is myInstance released?? and thereby not valid to my function anymore?
}

How can I safely use the returned autoreleased object inside my runIt method if I don't know when the autorelease happens? Should I retain the object returned by the createNewTest? Or can I safely use it within the runIt scope?

like image 650
Mads Lee Jensen Avatar asked Mar 04 '11 10:03

Mads Lee Jensen


People also ask

What is Objective-C memory management?

It is the process by which the memory of objects are allocated when they are required and deallocated when they are no longer required.

What is Autorelease Objective-C?

The -autorelease message is a deferred -release message. You send it to an object when you no longer need a reference to it but something else might. If you are using NSRunLoop, an autorelease pool will be created at the start of every run loop iteration and destroyed at the end.

What is Objective-C in iOS?

Objective-C is the primary programming language you use when writing software for OS X and iOS. It's a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime.

Does Objective-C Arc?

All Objective-C and Objective-C++ code should be compiled with ARC enabled.


1 Answers

An autoreleased object is added to an autorelease pool.

Objects in the autorelease pool are released at the end of an iteration of the main runloop (or sooner if you are managing your own autorelease pool and/or if you call drain).

When you call a method that returns an autoreleased object, it is pretty much guaranteed to stay valid until at least the end of the scope that it was called in.

If you want to ensure that it stays alive longer then you should retain it, remembering to release it again when you're finished with it.

like image 155
Jasarien Avatar answered Oct 04 '22 14:10

Jasarien