Question

I am trying to understand what is happening in the getter below, this is what I understand so far:

(1) the getter returns a pointer to an NSString object. (2) the NSString object is retained, possibly because we have just given away a pointer to it. (3) autorelease? when does that activate, when the PlanetClass instance is deallocated (released)?

// CLASS
@interface PlanetClass : NSObject {
        NSString *planetName;
}
- (NSString *)planetName;
- (void)setPlanetName:(NSString *)value;
@end

// GETTER
- (NSString *)planetName{
        return[[planetName retain] autorelease];
}

EDIT: I think I am more confused regarding the reason for the actual retain and later release. my understanding was that the getter simply returned a pointer to either nil or an object that already exists (i.e. was set by the setter) I think I understand the retain as we are giving away a pointer and we need to track that, but what about the release, is that just a failsafe incase I later forget to release the NSString object?

The instance variable planetName is also release in my dealloc method (see below) autorelease seems to be doing the same, just later when the pool is drained?

- (void)dealloc {
        [planetName release];
        [super dealloc];
}

cheers -gary-

Was it helpful?

Solution

It might be a good idea to let Objective-C handle this as a property, letting you clean up some of the implementation to keep the memory management, well, manageable:

@interface PlanetClass : NSObject {
    NSString* planetName;
}
@property(nonatomic, retain) NSString* planetName;
@end // PlanetClass

@implementation PlanetClass
@synthesize planetName
//... rest of PlanetClass here
@end // PlanetClass

There are plenty of docs available online for more details on Objective-C properties and @synthesize.

Memory Management Docs

I highly recommend this read from Apple on memory management to try and help understand what all the retain/release hubbub is about.

OTHER TIPS

When autorelease is sent to an object, it is added to the autorelease pool. When the pool is drained, it sends release to all the objects in the pool. So any object in the autorelease pool will be release when the pool is drained

The return/autorelease in the getter method is not doing anything, you can just return planetName

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top