0

我有以下课程:

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

@property (assign) Point2D* position;
@property (assign) Vector2D* vector;
@property (assign) CGSize size;

...

@end

及其实现:

@implementation Object2D

@synthesize position;
@synthesize vector;
@synthesize size;

- (id)init
{
    if (self = [super init])
    {
        position = [[Point2D alloc] init];
        vector = [[Vector2D alloc] init];
        size.width = kDefaultSize;
        size.height = kDefaultSize;
    }

    return self;
}

当我创建一个实例时Object2D,我正在这样做:

- (void) init
{
    // Create a ball 2D object in the upper left corner of the screen
    // heading down and right
    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对象和两个Vector2D对象,因为我在 Object2D init 方法中创建了 Point2D 和 Vector2d 的实例。

@class Vector2D;

@interface Point2D : NSObject
{
    CGFloat X;
    CGFloat Y;
}


@interface Vector2D : NSObject
{
    CGFloat angle;
    CGFloat length;
    Point2D* endPoint;
}

Object2D、Point2D 和 Vector2D 类没有 dealloc 方法。

有什么建议吗?

4

2 回答 2

0

是的,你是。此外,如果您在属性上有“保留”属性,那么像这样的行......

ball.position = [[Point2D alloc] initWithX:0.0 Y:0.0];

是你需要的内存泄漏......

ball.position = [[[Point2D alloc] initWithX:0.0 Y:0.0] autorelease];

或者

Point2D *point = [[Point2D alloc] initWithX:0.0 Y:0.0];
ball.position = point;
[point release];
于 2011-06-15T14:10:55.700 回答
0

是的,您正在为每个类创建两个实例。dealloc即使您自己没有声明它们,它们也确实具有内置方法。我会制作 Point2D 类的 X 和 Y属性,这样您就可以在没有您的initWithX:Y:方法的情况下更改它们,只需使用aPoint.X等。

更一般地说,我建议避免像您在此处所做的那样使用 Objective-C 对象。当您的数据可以轻松地包含在结构中时,它可以使您的代码更加精简,以避开 Objective-C 方法和内存管理的疯狂世界。

于 2011-06-15T14:12:05.527 回答