VansFannel
VansFannel

Reputation: 45991

doubts about setters and getters

I have a class, Object2D, with the following interface:

@class Point2D;
@class Vector2D;

@interface Object2D : NSObject
{
    Point2D* position;
    Vector2D* vector;
    ShapeType figure;
    CGSize size;
}

@property (assign) CGSize size;
@property ShapeType figure;

- (Point2D*) position;
- (void)setPosition:(Point2D *)pos;
- (Vector2D*) vector;
- (void)setVector:(Vector2D *)vec;
- (id)initWithPosition:(Point2D*)pos vector:(Vector2D*)vec;
- (void)move:(CGRect)bounds;
- (void)bounce:(CGFloat)boundryNormalAngle;
- (void)draw:(CGContextRef)context;

@end

And implementation:

@implementation Object2D

@synthesize size;
@synthesize figure;

- (Point2D*) position
{
    return position;
}
- (void)setPosition:(Point2D *)pos
{
    if (position != nil) {
        [position release];
    }
    position = pos;
}

- (Vector2D*) vector
{
    return vector;
}

- (void)setVector:(Vector2D *)vec
{
    if (vector != nil) {
        [vec release];
    }
    vector = vec;
}

...

- (void) dealloc
{
    if (position != nil) {
        [position release];
    }
    if (vector != nil) {
        [vector release];
    }
}

I don't use @synthesize with position and vector because I think, I have to release them before change their values.

I have two question:

If I want to get position value, is this correct? Will I get a reference to position or a new one?

ball = [[Object2D alloc] init];
ball.position = [[Point2D alloc] initWithX:0.0 Y:0.0];
ball.vector = [[Vector2D alloc] initWithX:5.0 Y:4.0];

Point2D* pos2;

pos2 = ball.position; <-- IS THIS CORRECT?

Second question:

Do I need to release previous values before assign new ones to position and vector?

Upvotes: 0

Views: 164

Answers (2)

VansFannel
VansFannel

Reputation: 45991

I've found an error on my code. Correct setters methods could be:

- (void)setPosition:(Point2D *)pos
{
    [pos retain];
    [position release];
    position = pos;
}

- (void)setVector:(Vector2D *)vec
{
    [vec retain];
    [vector release];
    vector = vec;
}

Upvotes: 0

Simon Lee
Simon Lee

Reputation: 22334

If you use...

@property (nonatomic, retain) Point2D *position;

and the same for vector it will do the retain / release for you. (and @synthesize them obviously!)

So if you do the following....

Point2D *newPosition = [[Point2D alloc] init];
[myObject setPosition:newPosition];
[newPosition release];

OR

[myObject setPosition:[[[Point2D alloc] init] autorelease]];

Then the retains / releases will be handled. You will need to add a dealloc to your Object2D class and do EITHER....

[position release];

OR

[self setPosition:nil];

both will release the object upon cleanup.

Upvotes: 3

Related Questions