2

我在尝试了解 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];
}
4

1 回答 1

0

-copyWithZone:(NSZone*)zone在您的班级中正确实施Point(或至少请在此处复制)

于 2012-06-24T06:57:13.303 回答