如何在方法中使用__weak来防止iOS中的内存泄漏

CGe*_*Gee 2 memory-leaks objective-c ios xcode-instruments automatic-ref-counting

我一直在尝试在iOS应用程序中进行一些模拟计算,但是我的手机会随着时间的推移而内存不足,它只是不会停止添加内存使用量,虽然我知道这种情况发生在哪里(用仪器钉它)我仍然不喜欢不知道我需要改变什么来阻止内存泄漏.

这是内存分配发生的方法,我知道我在这里添加新数据,但我认为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;
Run Code Online (Sandbox Code Playgroud)

我需要做一些__weak的东西吗?我不知道怎么样,有人可以帮助我吗?

小智 5

我不确定这会有所帮助,但值得一试.尝试在你的循环中放入一个autoreleasepool.

while (round < _maxRounds) {

    @autoreleasepool
    {
    ...
    }
}
Run Code Online (Sandbox Code Playgroud)