我正在开发一个iPhone应用程序。
我有以下属性:
@property (nonatomic, retain) Point2D* endPoint;这是同一个类上的一个方法:
- (id)initWithX:(CGFloat)x Y:(CGFloat)y;
{
if (self = [super init])
{
endPoint = [[Point2D alloc] initWithX:x Y:y];
...
}最后是同一个类上的dealloc方法:
- (void)dealloc {
[endPoint release];
[super dealloc];
}我的问题是这个代码是正确的吗?
endPoint = [[Point2D alloc] initWithX:x Y:y];或者我必须在这里做一个自动释放。
发布于 2011-07-02 00:12:37
你的作业
endPoint = [[Point2D alloc] initWithX:x Y:y];
不会增加retainCount,因此如果您想保留endPoint供以后使用,请不要在此处使用autorelease。
或者您可以像这样使用
self.endPoint = [[[Point2D alloc] initWithX:x Y:y] autorelease];
=>此赋值将增加endPoint的计数器。
发布于 2011-07-02 00:10:48
请阅读memory management guide,因为它将解释所有这些和更多内容。
简而言之,该代码是正确的。
如果你做了self.endPoint = [... alloc/init ...],那么你需要在init中自动释放或释放,以平衡额外的保留。
发布于 2011-07-02 00:11:08
将endPoint = [[Point2D alloc] initWithX:x Y:y];更改为
Point2D *temp = [[Point2D alloc] initWithX:x Y:y];
self.endPoint = temp;
[temp release];以利用属性保留setter。
https://stackoverflow.com/questions/6550422
复制相似问题