C Returning Autoreleased Copies

A strange issue I've come across trying to understand Apple's Memory Management standards. Lets say I have a method that returns a copy without letting the user know that it is a copy.

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

The problem is that Xcode's Analyze function flags this as an object being sent too many -autorelease calls. I'm assuming this is because -copy implicitly assumes that you are taking ownership, and thus the possibility of +0 retain count is likely. But I'm not entirely sure.

Xcode's Analyze Information

+(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.
}

Any tips or hints on why this is happening? Unless I'm missing something, the code should work fine because the autorelease wont trigger until a safe time (ie it works kind of like a convenience constructor, user has time to retain.)

As per request, -copyWithZone: would be implemented as such:

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

在您的Point类中正确地执行-copyWithZone:(NSZone*)zone (或者至少请复制它在这里)

链接地址: http://www.djcxy.com/p/53280.html

上一篇: Javascript添加一个PHP文件

下一篇: C返回自动发行副本