1

I have a QuantumClone class which has an array of CGPoints. The single QuantumPilot object creates a QuantumClone at the beginning of each level. During the next level the QuantumPilot records its velocities to its QuantumClone. At the beginning of a new level the game loop runs this code

QuantumClone *c = [[self.pilot clone] copy];
c.bulletDelegate = self;
c.weapon = self.pilot.weapon;
[self.clones addObject:c];

But eventually the game will be reset and each QuantumClone object in the clones NSMutableArray will be removed.

Am I leaking memory by assigning values to the CGPoint pastVelocities[4551] ?

How do I reset these? I can't release them since they are not Objective-C objects. Do I need to call C functions to release this memory?

@interface QuantumClone : QuantumPilot <NSCopying> {
  CGPoint pastVelocities[4551];
}

- (id)copyWithZone:(NSZone *)zone {
    QuantumClone *c = [[[QuantumClone alloc] init] autorelease];
    c.weapon = self.weapon;
    for (NSInteger i = 0; i < 4551; i++) {
        [c recordVelocity:pastVelocities[i] firing:pastFireTimings[i]];
    }
    [c recordLatestIndex:timeIndex];
    return c;
}

- (void)recordVelocity:(CGPoint)vel firing:(BOOL)firing {
    CGPoint p = pastVelocities[timeIndex];
    p.x = vel.x;
    p.y = vel.y;
    pastVelocities[timeIndex] = p;
    bool fired = firing;
    pastFireTimings[timeIndex] = fired;
    timeIndex++;
}

@interface QuantumPilot : CCNode {}
....
@property (nonatomic, retain) QuantumClone *clone;

- (void)copyDeltas {
    [self.clone recordVelocity:ccp(self.vel.x, -self.vel.y) firing:self.firing];
}

- (void)createClone {
    self.clone = [[[QuantumClone alloc] init] autorelease];
    self.clone.active = YES;
    self.clone.weapon = self.weapon;
}
4

2 回答 2

2

我是否通过为 CGPoint 分配值来泄漏内存pastVelocities[4551]

简短的回答:没有。

长答案:代码中的数组是一大块连续内存,所有CGRects 都在其中,并且它具有自动存储功能,这意味着它将自动分配和释放(当它超出范围时)。换句话说,当其父对象被销毁时,该数组将与这 4551 个对象一起消失。

您可以通过打印结果来验证它的大小sizeof(pastVelocities)。将结果除以sizeof(CGRect)将告诉您可以在其中存储多少此类对象。

解除分配必须与显式分配结合。您只需要释放动态(显式)分配的内存,例如,使用alloc函数族(malloc、calloc、realloc 等)。

我该如何重置这些?

memset(pastVelocities, 0, sizeof(pastVelocities));

这将重置整个阵列。

于 2014-10-11T01:22:17.210 回答
1

jweyrich 打败了我,但我会继续发布这个以防万一;)

——</p>

你没有泄漏。运行时分配足够的内存来保存所有 ivars。在这种情况下,每个 QuantumClone 实例将使用比 QuantumPilot 多约 18k(64 位上约 36k)的内存,因为您已告诉运行时它需要为 4551 个 CGPoints 分配足够的 ivar 存储。

如果 pastVelocity 是 aCGFloat *而不是 a CGFloat[4551],则需要手动分配内存,malloc然后调用free. -dealloc但是,通过将其声明为固定大小的 C 数组,运行时会对其进行处理(但代价是使每个 QuantumClone 成为一个相当大的对象)。

也就是说,整个方法似乎很脆弱。为什么是 4551?为什么选择 C ​​数组?使用 C 数组来提高性能并没有错,但我强烈怀疑这是过早的优化。

于 2014-10-11T01:27:31.067 回答