When you synthesize a property (see below)
@interface CelestialBody : NSObject {
NSString *name;
}
...
@interface Planet : NSObject {
NSString *name;
int mass;
CelestialBody *moon;
}
@property(nonatomic, retain) NSString *name;
@property(assign) int *mass;
@property(nonatomic, retain) CelestialBody *moon;
...
@implementation Planet
@synthesize name;
@synthesize mass;
@synthesize moon;
...
You get setters and getters for each of the iVars (i.e.)
[newPlanet setName:@"Jupiter"];
[newPlanet setMass:57];
NSString *closestName = [newPlanet name];
int largestMass = [newPlanet mass];
CelestialBody *newMoon = [[CelestialBody alloc] initWithName:@"Callisto"];
[self setMoon:newMoon];
[newMoon release];
but you also get the ability to release the object using …
// Releases the object (frees memory) and sets the object pointer to nil.
[self setMoon: nil];
There will of course be deallocs for each Class.
// Moon
-(void)dealloc {
[name release];
[super dealloc];
}
// Planet
-(void)dealloc {
[name release];
[moon release];
[super dealloc];
}
Am I getting this right?
gary
Unless your planet object is declared as a property within some other class, using the retain/copy attributes, you can’t release it this way.
When you declare a property using retain/copy, the resulting setter will release the old value and assign the new value, retaining or copying it in the process. If you pass nil, you will release the old value and assign nil, retaining or copying it, and retaining/copying nil is nil, so effectively you end up releasing the old value and assigning nil to the ivar.
This is an acceptable way to release instance variables.
In order to be able to release your newPlanet instance this way, you’d have to have declared it in a class as a property with either retain or copy.
As a further example, since your planet object declares its properties in this way, you could release those using this method.
Or in the Planet class’s dealloc method, you could do:
This would release name and assign nil to it.