Objective c 目的-c2.0;转让财产;内存泄漏?

Objective c 目的-c2.0;转让财产;内存泄漏?,objective-c,iphone,memory-management,Objective C,Iphone,Memory Management,我还在学习Objective-C内存管理。我试图在我正在构建的示例程序中实现几个简单的类 例如,假设我有以下类定义: #import <UIKit/UIKit.h> @interface customViewController : UIViewController { customObject *myCustomObject; } @property (retain) customObject *myCustomObject; - (void)repla

我还在学习Objective-C内存管理。我试图在我正在构建的示例程序中实现几个简单的类

例如,假设我有以下类定义:

 #import <UIKit/UIKit.h>

 @interface customViewController : UIViewController 
 {
    customObject *myCustomObject;
 }

 @property (retain) customObject *myCustomObject;

 - (void)replaceCustomObject:(customObject *)newObject;

 @end
然后,请假设在customViewController实例中,myCustomObject已设置为有效值并正在使用。然后,方法replaceCustomObject被定义为:

 - (void)replaceCustomObject:(customObject *)newObject
 {
     //Does this cause a memory leak because I just assign over
     //the existing property? 
     self.myCustomObject = newObject;
 }
正如注释所问,这会泄漏内存吗?或者这是用新对象替换以前对象的有效方法吗

谢谢你,

Frank

这是完全有效的,并且不会泄漏内存。合成访问器正确管理保留计数


(顺便说一句,您不需要replaceCustomObject:method;因为您的属性默认为readwrite,所以您有一个自动生成的setCustomObject:method,您的类的客户端可以使用它,它遵循正常的Cocoa命名约定。)

属性访问器语法

self.x = y;
与显式调用setter方法具有相同的效果:

[self setX:y];
访问器方法将执行它编写的任何操作。在您的情况下,对于已@property(retain)合成的@property属性,访问器将释放旧对象并保留新对象

因此,无论是显式地还是通过“.”语法调用setter,都将做正确的事情,包括正确的内存管理

简而言之:不,这不会泄漏内存。

根据,如果在声明中使用(retain),则合成方法将首先释放旧值,然后保留新值:

if (property != newValue) {
    [property release];
    property = [newValue retain];
}

正如其他人提到的,您的代码是完全有效的,并且在分配给属性时不会泄漏内存

如果您忘记实施适当的
dealloc
方法,则在销毁
customViewController
时,最后分配的对象将泄漏。适当的
dealloc
实现如下所示:

- (void)dealloc
{
    self.myCustomObject = nil;
    [super dealloc];
}

我知道我不需要replaceCustomObject:方法。这只是我用来说明我的总体目标的一种方式。正如您所想象的,我所使用的不仅仅是分配一个属性。:-)谢谢你回答我的问题。你能进一步解释一下吗?我从未见过将属性设置为零。这是否等于执行[self.myCustomObject释放]?这就是我学习如何在dealloc方法中处理此问题的方式…发送[self.myCustomObject release]是危险的,因为这样做之后,self.myCustomObject仍然指向现在发布的对象!在dealoc方法中,它可能是安全的,因为self无论如何都会被破坏,但我不喜欢有特殊的规则要记住。为了安全起见,您还可以执行以下操作:[myCustomObject release];myCustomObject=nil;
- (void)dealloc
{
    self.myCustomObject = nil;
    [super dealloc];
}