SpriteKit保留周期或内存泄漏

时间:2015-07-16 04:45:25

标签: macos memory-leaks sprite-kit retain-cycle

我的SpriteKit游戏现在有三个场景; Menu.mLevelSelect.mLevel.m。当我启动应用程序时,内存使用量为35MB。从主菜单转换到关卡选择场景后,它几乎保持在35MB左右。从关卡选择场景移动到关卡本身,它最高可达150MB。当然,在创建关卡时会涉及更多精灵和类。但是,当我通过我作为精灵的叠加菜单重新加载关卡时,每次重新加载时内存使用量会继续增加约2MB。这可能是保留周期问题吗?如果我切换回水平选择场景然后重新进入水平本身,记忆继续攀爬和爬升,情况也是如此。我担心我的状态机的实现。我将在下面发布一些骨架代码:

LevelScene.m

-(void)didMoveToView:(SKView *)view {
    ...
    [self initGameStateMachine];
    ...
}

...
//other methods for setting up the level present
...

-(void) initGameStateMachine {
    LevelSceneActiveState *levelSceneActiveState = [[LevelSceneActiveState alloc] initLevelScene:self];
    LevelSceneConfigureState *levelSceneConfigureState = [[LevelSceneConfigureState alloc] initLevelScene:self];
    LevelSceneFailState *levelSceneFailState = [[LevelSceneFailState alloc] initLevelScene:self];
    LevelSceneSuccessState *levelSceneSuccessState = [[LevelSceneSuccessState alloc] initLevelScene:self];

    NSMutableDictionary *states = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                   levelSceneActiveState, @"LevelSceneActiveState",
                                   levelSceneConfigureState, @"LevelSceneConfigureState",
                                   levelSceneFailState, @"LevelSceneFailState",
                                   levelSceneSuccessState, @"LevelSceneSuccessState",
                                   nil];

    _gameStateMachine = [[StateMachine alloc] initWithStates:states];
    [_gameStateMachine enterState:levelSceneActiveState];
}


-(void)update:(CFTimeInterval)currentTime {
    //update the on screen keyboard with notes that are being played

    [_gameStateMachine updateWithDeltaTime:[NSNumber numberWithDouble:currentTime]];
}


-(void) willMoveFromView:(SKView *)view {
    [self removeAllChildren];
}

StateMachine.m

#import "StateMachine.h"
#import "GameState.h"

@interface StateMachine()

@property NSMutableDictionary *states;

@end

@implementation StateMachine

-(instancetype)initWithStates:(NSMutableDictionary*)states {
    if (self = [super init]) {
        for (id key in [states allValues]) {
            if (![key conformsToProtocol:@protocol(GameState)]) {
                NSLog(@"%@ does not conform to @protocol(GameState)", key);
                return nil;
            }
        }
        _states = states;
    }
    return self;
}

//this method will be used to start the state machine process
-(bool)enterState:(id)nextState {
    if (!_currentState) {
        _currentState = [_states objectForKey:[nextState className]];
        [[NSNotificationCenter defaultCenter] addObserver:_currentState selector:@selector(keyPressed:) name:@"KeyPressedNotificationKey" object:nil];
        return YES;
    }
    else if ([_currentState isValidNextState:nextState]) {
        [_currentState performSelector:@selector(willLeaveState)];
        _currentState = [_states objectForKey:[nextState className]];
        [[NSNotificationCenter defaultCenter] addObserver:_currentState selector:@selector(keyPressed:) name:@"KeyPressedNotificationKey" object:nil];
        return YES;
    }
    return NO;
}

-(void)updateWithDeltaTime:(NSNumber*)currentTime {
    [_currentState performSelector:@selector(updateWithDeltaTime:) withObject:currentTime];
}

@end

LevelSceneActiveState //这是4个州之一

#import "LevelSceneActiveState.h"
#import "LevelSceneConfigureState.h"
#import "LevelSceneSuccessState.h"
#import "LevelSceneFailState.h"
#import "StateMachine.h"
#import "LevelScene.h"
#import "SSBitmapFontLabelNode.h"


@interface LevelSceneActiveState()

@property LevelScene *levelScene;

@end

@implementation LevelSceneActiveState

-(instancetype)initLevelScene:(LevelScene *)levelScene {
    if (self = [super init])
        _levelScene = levelScene;
    return self;
}

-(void)updateWithDeltaTime:(NSNumber*)currentTime {
    //game variables created here
    ....

    //state machine needs to be set here...if set in init, it does not have a value in the LevelScene yet
    if (_gameStateMachine == nil)
        _gameStateMachine = _levelScene.gameStateMachine;

    //game logic performed here
    ...

    //check for timer finishing
    if (!_levelScene.timer.isValid) {
        //success
        if (_levelScene.score >= 7) {
            [_gameStateMachine enterState:LevelSceneSuccessState.self];
        }
        else { //failure
            [_gameStateMachine enterState:LevelSceneFailState.self];
        }
    }

}

//another class is used to trigger notifications of key presses
-(void) keyPressed:(NSNotification*)notification {
    NSNumber *keyCodeObject = notification.userInfo[@"keyCode"];
    NSInteger keyCode = keyCodeObject.integerValue;

    if (keyCode == 53)
        [self escapePressed];
}

-(void) escapePressed {
    [_gameStateMachine enterState:LevelSceneConfigureState.self];
    [_levelScene childNodeWithName:@"timer"].paused = YES;
}

-(bool)isValidNextState:(id)nextState {
    if ([[nextState className] isEqualToString:@"LevelSceneConfigureState"])
        return YES;
    ...

    return NO;
}

//this makes sure that we're not notifying an object that may not exist
-(void) willLeaveState {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"KeyPressedNotificationKey"
                                                  object:nil];
}

@end

在状态之间切换时,我不希望LevelScene场景消失。我知道这很难诊断,尤其是当你没有坐在整个项目前面时。我可以做些什么来自我诊断?任何有用的提示/技巧都会很棒。

[更新]我尝试了Product-> Profile-> Instruments->分配的事情,但我不知道如何处理它。记忆显示它继续上升。

1 个答案:

答案 0 :(得分:3)

仪器教程文章

对于那些在使用Xcode乐器方面和我一样无能为力的人来说,这里有一个来自 Ray Wenderlich amazing article,真是愚蠢了!

我在项目中发现了很多问题,因为那篇文章我甚至认为不是问题。我并不感到惊讶,没有人就这个问题发表了答案,因为当你遇到这些类型的问题时,他们对你正在进行的项目非常个人化并且很难调试。

我的问题+解决方案

我的问题很常见。当我的场景重新加载时,我正在加载一组资源,在这种情况下是一个.sf2(声音字体)文件,一遍又一遍。我老实以为我已经把所有精灵都摆脱了这个问题。

以下是我使用仪器发现它的方法:

  • 在Xcode中转到Product - > Profile,然后选择Allocations

此窗口应弹出: Allocations Instrument in Xcode

  • 点击左上方的red circle按钮(这将启动您的应用)
  • 在您的应用中执行似乎会导致问题的操作,然后按Mark Generation
  • 重复导致问题的操作,然后继续按Mark Generation
    注意:Mark Generation此时会获取应用的快照,以便您可以看到内存中的更改

Pressing the <code>mark generation</code> button



  • 停止应用程序运行,然后潜入其中一代(我选择了Generation C,因为那时内存使用的差异变得不变) After pressing the <code>mark generation</code> button several times
  • 显示为AVAudioUnitSampler的我的采样器(SamplerState对象)正在分配一堆内存 Sampler object

  • 我点击SamplerState右侧的小箭头,它将我带入此视图(显示了大量分配内存的项目) Sampler items

  • 单击其中一个并单击extended details按钮将允许您查看此项目的堆栈跟踪 Extended details info

  • 我双击了我认为会成为问题的方法 enter image description here

  • 双击该方法后,会显示另一个视图,其中包含您的代码以及代码行分配最多内存的百分比(非常有用!)
    注意:在我的情况下,罪魁祸首是每次重新加载关卡时分配大约1.6MB!忽略注释掉的代码,我在修复问题后拍摄了已保存会话的屏幕截图。 enter image description here

  • 修复我的代码后,不再有任何主要的内存分配了......尽管我还有一些东西可以清理!级别重新加载之间只有33KB,这要好得多! enter image description here