2011-06-16 26 views
0

我有一個類,Object2D,具有以下接口:疑慮和getter

@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

回答

3

如果您使用...

@property (nonatomic, retain) Point2D *position; 

與同爲載體,將做保留/釋放你。 (和@synthesize他們明顯!)

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

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

OR

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

然後保留/釋放將被處理。您將需要一個dealloc的添加到您的Object2D類,並請執行....

[position release]; 

OR

[self setPosition:nil]; 

都將在清理釋放對象。

+0

因此,如果我使用這些,我不會在setter方法上進行發佈,不是嗎?對不起,但我不太懂英文。 – VansFannel 2011-06-16 12:06:30

+1

如果你使用這些,那麼你就不需要編寫任何特定的setter方法,它們將在你處理retain/release的時候爲你創建。 – 2011-06-16 12:11:32

+0

好的,如果我有一個Point2D的實例,並且我改變位置值,我不會有內存泄漏,不是嗎? – VansFannel 2011-06-16 12:13:02

0

我在代碼中發現了一個錯誤。正確的setter方法可能是:

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

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