2

我一直在尝试在 iOS 应用程序中进行一些模拟计算,但是随着时间的推移,我的手机内存不足,它只是不会停止增加内存使用量,尽管我知道这发生在哪里(用 Instruments 确定)我仍然没有不知道我需要改变什么来阻止内存泄漏。

这是发生内存分配的方法,我知道我在这里添加了新数据,但我认为 ARC 会释放我无法再引用的所有已分配数据?

int round = 0;

InstanceInSimulation *simulatingChosen = [[InstanceInSimulation alloc] initWithSimulationInstance:_chosenInstance];
InstanceInSimulation *simulatingOpponent = [[InstanceInSimulation alloc] initWithSimulationInstance:_opponentInstance];

while (round < _maxRounds) {

    // first choose action
    NSManagedObject *chosensAction = [simulatingChosen nextActionAgainstOpponent:simulatingOpponent];
    NSManagedObject *opponentsAction = [simulatingOpponent nextActionAgainstOpponent:simulatingChosen];

    // second calculate which action first
    InstanceInSimulation *attackingFirst;
    InstanceInSimulation *defendingFirst;
    NSManagedObject *attackingFirstsAction;
    NSManagedObject *defendingFirstsAction;

    if (simulatingChosen.instance.speed > simulatingOpponent.instance.speed) {
        attackingFirst = simulatingChosen;
        defendingFirst = simulatingOpponent;
        attackingFirstsAction = chosensAction;
        defendingFirstsAction = opponentsAction;
    } else {
        attackingFirst = simulatingOpponent;
        defendingFirst = simulatingChosen;
        attackingFirstsAction = opponentsAction;
        defendingFirstsAction = chosensAction;
    }

    // memory savings
    chosensAction = nil;
    opponentsAction = nil;

    // third calculate
    [self calculateSomething]; // this is not the memory problem

    // memory savings
    attackingFirst = nil;
    attackingFirstsAction = nil;
    defendingFirst = nil;
    defendingFirstsAction = nil;

    round++;
}

// memory savings
simulatingChosen = nil;
simulatingOpponent = nil;

我需要做一些 __weak 的事情吗?我不知道怎么做,有人可以帮我吗?

4

2 回答 2

5

我不确定这会有所帮助,但值得一试。尝试在循环中放置一个自动释放池。

while (round < _maxRounds) {

    @autoreleasepool
    {
    ...
    }
}
于 2013-07-14T22:19:38.440 回答
1

您所看到的不是内存泄漏,正在积累的内存仍然被自动释放池引用。您正在 while 循环中创建自动释放的对象,但自动释放池永远不会耗尽。

就像 Ahmed 建议的那样,在循环中创建一个新的自动释放池:

while (round < _maxRounds) {
    @autoreleasepool {
         // your code here
    }
}

查看Advanced Memory Management Programming Guide 中的Using Autorelease Pool Blocks

于 2013-07-14T23:51:23.747 回答