在分析我的应用程序之后,我似乎在这个方法中的某个地方出现了内存泄漏:
- (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,为什么乐器指向这个位置呢?这种方法是如何导致泄漏的?
- 提前谢谢
答案 0 :(得分: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
更快的替代方案。
希望这是问题,很容易修复。
答案 1 :(得分:1)
您不断创建BallNode类的越来越多的实例。尝试在最后一个if语句之后添加ball = nil;
但老实说我不知道这是否会对你有帮助。
您的代码逻辑是错误的,或者您没有发布其他内容。通常你有一个你的球的ivar你应该使用发布的代码是有意义的。