Iphone 释放还是不释放

Iphone 释放还是不释放,iphone,objective-c,memory-management,Iphone,Objective C,Memory Management,我正在开发一个iPhone应用程序 我拥有以下财产: @property (nonatomic, retain) Point2D* endPoint; 这是同一类上的一个方法: - (id)initWithX:(CGFloat)x Y:(CGFloat)y; { if (self = [super init]) { endPoint = [[Point2D alloc] initWithX:x Y:y]; ... } - (void)dealloc

我正在开发一个iPhone应用程序

我拥有以下财产:

@property (nonatomic, retain) Point2D* endPoint;
这是同一类上的一个方法:

- (id)initWithX:(CGFloat)x Y:(CGFloat)y;
{
    if (self = [super init])
    {
        endPoint = [[Point2D alloc] initWithX:x Y:y];

    ...
}
- (void)dealloc {
    [endPoint release];
    [super dealloc];
}
最后是同一类上的dealoc方法:

- (id)initWithX:(CGFloat)x Y:(CGFloat)y;
{
    if (self = [super init])
    {
        endPoint = [[Point2D alloc] initWithX:x Y:y];

    ...
}
- (void)dealloc {
    [endPoint release];
    [super dealloc];
}
我的问题是这个代码正确吗

endPoint = [[Point2D alloc] initWithX:x Y:y];
或者我必须在这里做一个自动释放

去读这本书,因为它会解释所有这些,还有更多

简而言之,该代码是正确的

如果您使用self.endPoint=[…alloc/init…],则需要在init中自动释放或释放,以平衡额外的保留。

请阅读,因为它将解释所有这些以及更多内容

简而言之,该代码是正确的

如果您使用self.endPoint=[…alloc/init…],则需要在init中自动释放或释放,以平衡额外的保留。

更改endPoint=[[Point2D alloc]initWithX:x Y:Y];到

利用保留setter的属性。

更改端点=[[Point2D alloc]initWithX:xy:Y];到

利用属性设置器。

您的作业

端点=[[Point2D alloc]initWithX:XY:Y]

不会增加重新计数,因此,如果希望保留端点以供以后使用,则不在此处使用autorelease

或者你可以这样使用

self.endPoint=[[Point2D alloc]initWithX:xy:Y]autorelease]

=>此分配将增加端点的计数器。

您的分配

端点=[[Point2D alloc]initWithX:XY:Y]

不会增加重新计数,因此,如果希望保留端点以供以后使用,则不在此处使用autorelease

或者你可以这样使用

self.endPoint=[[Point2D alloc]initWithX:xy:Y]autorelease]


=>此分配将增加endPoint的计数器。

您不应直接使用endPoint,而应通过self.endPoint使用

@property (nonatomic, retain) Point2D* endPoint;

- (id)initWithX:(CGFloat)x Y:(CGFloat)y;
{
    if (self = [super init])
    {
        self.endPoint = [[[Point2D alloc] initWithX:x Y:y] autorelease]; //It'll retain it for us.

    ...
}

- (void)dealloc {
    self.endPoint = nil; //setting it to nil means it'll release the object it was previously pointing to.
    [super dealloc];
}

您不应该直接使用端点,而应该通过self.endPoint使用端点

@property (nonatomic, retain) Point2D* endPoint;

- (id)initWithX:(CGFloat)x Y:(CGFloat)y;
{
    if (self = [super init])
    {
        self.endPoint = [[[Point2D alloc] initWithX:x Y:y] autorelease]; //It'll retain it for us.

    ...
}

- (void)dealloc {
    self.endPoint = nil; //setting it to nil means it'll release the object it was previously pointing to.
    [super dealloc];
}

在没有平衡释放的情况下,它会在某处泄漏。我会直接设置ivar;避免任何设置器覆盖的疯狂。如果没有平衡释放,它会泄漏到哪里。我会直接设置ivar;避免任何二传超控疯狂;在init/dealloc中,有很多理由直接转到ivar。@bbum true,但在这种情况下,最好只使用该属性。不,实际上不是。如果setter/getter已在子类中被重写,则您将被忽略。如果存在一个具有自定义行为的setter/getter,那么它将在初始化/解除分配期间被激发,正好是在对象处于未定义状态时。请注意,不要投反对票——实际上这没什么大不了的,但肯定有一些陷阱需要注意;在init/dealloc中,有很多理由直接转到ivar。@bbum true,但在这种情况下,最好只使用该属性。不,实际上不是。如果setter/getter已在子类中被重写,则您将被忽略。如果存在一个具有自定义行为的setter/getter,那么它将在初始化/解除分配期间被激发,正好是在对象处于未定义状态时。请注意,不要投反对票——实际上这没什么大不了的,但肯定有一些陷阱需要注意。