Objective-C返回自动释放的副本

时间:2012-06-24 06:54:52

标签: objective-c memory-management copy autorelease

我遇到一个奇怪的问题,试图了解Apple的内存管理标准。假设我有一个方法可以返回副本,而不会让用户知道它是副本。

+(Point2D*) Add:(Point2D*)a To:(Point2D*)b
{
        Point2D * newPoint = [a copy];
        [newPoint Add:b]; // Actually perform the arithmetic.
        return [newPoint autorelease];
}

问题是Xcode的Analyze函数将此标记为发送太多-autorelease调用的对象。我假设这是因为-copy隐含地假设您正在拥有所有权,因此可能会有+0保留计数的可能性。但我不完全确定。

Xcode的分析信息

+(Point2D*) Add:(Point2D*)a To:(Point2D*)b
{
        Point2D * newPoint = [a copy]; // <- 1. Method returns an Objective-C object with a +0 retain count.
        [newPoint Add:b];
        return [newPoint autorelease]; // <- 2. Object sent -autorelease method.
                                       // <- 3. Object returned to caller with a +0 retain count.
                                       // <- 4. Object over -autoreleased: object was sent -autorelease but the object has zero (locally visible) retain counts.
}

有关为何发生这种情况的任何提示或提示?除非我遗漏了某些东西,否则代码应该可以正常工作,因为自动释放不会触发直到安全时间(即它有点像便利构造函数,用户有时间保留。)

根据请求,-copyWithZone:将实现如下:

-(id)copyWithZone:(NSZone *)zone
{
        return [[Point2D allocWithZone:zone] initX:x Y:y Z:z];
}

1 个答案:

答案 0 :(得分:0)

-copyWithZone:(NSZone*)zone课程中正确实施Point(或至少请在此处复制)