Stefan Fachmann
Stefan Fachmann

Reputation: 545

the autorelease of an object in a ObjC program

Here we have some examples from About Memory Management

In the first example

- (NSString *) fullName {
    NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName,       self.lastName] autorelease];
    return string;
}

In this example is how the above method is called

{
   Person *aPerson = [[Person alloc] init];
   NSString *name = aPerson.fullName;
   [aPerson release];
}

So I assume that the *name is autoreleased after code flow reaches the closing curly braces.

Is that true?

And in general autorelease of an object, depends on the scope and lifetime of the variable which references that object.

Are there any criteria which manage the autorelease pool of objects in a Objective-C program?

Thanks.

Upvotes: 0

Views: 113

Answers (1)

Lvsti
Lvsti

Reputation: 1525

Release of an autoreleased object takes place when the autorelease pool which the object has been pushed to by autorelease is released/drained explicitly, provided that the object's retain count at that moment is 0+ (that is, nobody else but the autorelease pool is retaining it).

An object is not getting autoreleased just because it has gone out of scope. In your example we can only say for sure that it won't get released before the closing curly brace, but as H2CO3 said, without the relevant source code we cannot predict when it is actually cleaned up. In Cocoa (Touch) apps, threads with runloops have a loop-level autorelease pool which they drain at the end of each runloop iteration. If your method is called from the runloop (e.g. as part of an event handler callback), autoreleased objects will be released shortly after the handler code returns; otherwise there is no such guarantee.

Note that the above holds for non-ARC environment; others may confirm whether it's still valid or not when using ARC.

Upvotes: 1

Related Questions