我有一個類,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];
}
}
我不使用@synthesize
與position
和vector
因爲我覺得,我必須在更改它們的值之前釋放它們。
我有兩個問題:
如果我想要得到的位置值,這是正確的?我會得到一個職位或一個新的參考?
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?
第二個問題:
我需要之前釋放先前值分配新來position
和vector
?
因此,如果我使用這些,我不會在setter方法上進行發佈,不是嗎?對不起,但我不太懂英文。 – VansFannel 2011-06-16 12:06:30
如果你使用這些,那麼你就不需要編寫任何特定的setter方法,它們將在你處理retain/release的時候爲你創建。 – 2011-06-16 12:11:32
好的,如果我有一個Point2D的實例,並且我改變位置值,我不會有內存泄漏,不是嗎? – VansFannel 2011-06-16 12:13:02