对安装者和吸气剂的疑虑

时间:2011-06-16 11:16:40

标签: objective-c getter-setter

我有一个班级Object2D,其中包含以下界面:

@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

并实施:

@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];
    }
}

我不会将@synthesizepositionvector一起使用,因为我认为,我必须在更改其值之前释放它们。

我有两个问题:

如果我想获得位置值,这是正确的吗?我会获得对职位或新职位的提及吗?

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?

第二个问题:

在将新的值分配给positionvector之前,是否需要先释放以前的值?

2 个答案:

答案 0 :(得分:3)

如果你使用......

@property (nonatomic, retain) Point2D *position;

和矢量相同,它会为你做保留/释放。 (显然@synthesize他们!)

所以如果你做了以下......

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

OR

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

然后将处理保留/释放。您需要在Object2D类中添加dealloc并执行EITHER ....

[position release];

OR

[self setPosition:nil];

两者都会在清理时释放对象。

答案 1 :(得分:0)

我的代码发现错误。正确的setter方法可能是:

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

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