2

在分析我的应用程序后,我似乎在这个方法的某个地方有内存泄漏:

- (void) didEvaluateActions {
for (int x = 0; x < self.children.count; x++) {
    if ([self.children[x] isKindOfClass:[BallNode class]]) {
        BallNode * ball = (BallNode *) self.children[x];

        if (abs(ball.physicsBody.velocity.dx) < BALL_MIN_VEL_X) {
            ball.physicsBody.velocity = CGVectorMake((ball.physicsBody.velocity.dx < 0 ? -1 : 1) * BALL_MIN_VEL_X, ball.physicsBody.velocity.dy);
        }

        if (abs(ball.physicsBody.velocity.dx) > BALL_MAX_VEL_X) {
            ball.physicsBody.velocity = CGVectorMake((ball.physicsBody.velocity.dx < 0 ? -1 : 1) * BALL_MAX_VEL_X, ball.physicsBody.velocity.dy);
        }

        if (abs(ball.physicsBody.velocity.dy) < BALL_MIN_VEL_Y) {
            ball.physicsBody.velocity = CGVectorMake(ball.physicsBody.velocity.dx, (ball.physicsBody.velocity.dy < 0 ? -1 : 1) * BALL_MIN_VEL_Y);
        }

        if (abs(ball.physicsBody.velocity.dy) > BALL_MAX_VEL_Y) {
            ball.physicsBody.velocity = CGVectorMake(ball.physicsBody.velocity.dx, (ball.physicsBody.velocity.dy < 0 ? -1 : 1) * BALL_MAX_VEL_Y);
        }
    }
}
}

仪器 我没有看到这种方法可能导致内存泄漏的地方。BallNode 不是在这里创建的,那么为什么仪器会指向这个位置呢?这种方法如何导致泄漏?

-预先感谢

4

2 回答 2

2

我似乎没有做错任何事情,但是如果您在代码中指向正确的位置,那么我认为这与self.children.count

尝试

NSUInteger count = self.children.count;

for (NSInteger x = 0; x < count; x++)
{
    if ([self.children[x] isKindOfClass:[BallNode class]]) {
        BallNode * ball = (BallNode *) self.children[x];

        if (abs(ball.physicsBody.velocity.dx) < BALL_MIN_VEL_X) {
            ball.physicsBody.velocity = CGVectorMake((ball.physicsBody.velocity.dx < 0 ? -1 : 1) * BALL_MIN_VEL_X, ball.physicsBody.velocity.dy);
        }

        if (abs(ball.physicsBody.velocity.dx) > BALL_MAX_VEL_X) {
            ball.physicsBody.velocity = CGVectorMake((ball.physicsBody.velocity.dx < 0 ? -1 : 1) * BALL_MAX_VEL_X, ball.physicsBody.velocity.dy);
        }

        if (abs(ball.physicsBody.velocity.dy) < BALL_MIN_VEL_Y) {
            ball.physicsBody.velocity = CGVectorMake(ball.physicsBody.velocity.dx, (ball.physicsBody.velocity.dy < 0 ? -1 : 1) * BALL_MIN_VEL_Y);
        }

        if (abs(ball.physicsBody.velocity.dy) > BALL_MAX_VEL_Y) {
            ball.physicsBody.velocity = CGVectorMake(ball.physicsBody.velocity.dx, (ball.physicsBody.velocity.dy < 0 ? -1 : 1) * BALL_MAX_VEL_Y);
        }
    }
}

您目前拥有它的方式是尝试通过循环评估 self.children.count 每次迭代。这不应该导致泄漏,但是在反复评估它时,引擎盖下可能有一些东西阻止它被正确释放。

此外,您可能希望将其enumerateChildNodesWithName:视为比查看每个孩子并查看它是否是BallNode.

希望这就是问题所在,并且很容易解决。

于 2015-03-26T04:29:33.877 回答
1

您不断创建越来越多的 BallNode 类实例。尝试ball = nil;在最后一个 if 语句之后添加,但老实说,我不知道这是否会对您有所帮助。

要么您的代码逻辑错误,要么您没有发布其他内容。通常,拥有一个球的 ivar 是有意义的,您可以将发布的代码应用到该 ivar 上。

于 2015-03-25T23:14:33.223 回答