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

}

Object2D init メソッドで Point2D と Vector2d のインスタンスを作成しているため、 2 つのPoint2Dオブジェクトと 2つのオブジェクトを初期化しているかどうかはわかりません。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

はい、これらの各クラスの 2 つのインスタンスを作成しています。また、dealloc自分で宣言していなくても、メソッドが組み込まれています。Point2D クラスのX プロパティと YプロパティinitWithX:Y:を作成して、メソッドを使用せずaPoint.Xに などを使用して変更できるようにします。

より一般的には、ここで行ったように、Objective-C オブジェクトの使用を避けることをお勧めします。データを構造体に簡単に含めることができる場合、コードをより合理化して、Objective-C メソッドとメモリ管理のクレイジーな世界を避けることができます。

于 2011-06-15T14:12:05.527 に答える
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 に答える