【问题标题】:SpriteKit Retain Cycle Or Memory LeakSpriteKit 保留周期或内存泄漏
【发布时间】:2015-07-16 04:45:24
【问题描述】:

我的 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 //这是四种状态之一

#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->Allocation 的东西,但我不知道如何处理它。内存表明它还在继续上升。

【问题讨论】:

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


    【解决方案1】:

    仪器教程文章

    对于像我一样在使用 Xcode 的 Instruments 方面一无所知的人,这里有一个来自 Ray Wenderlichamazing article,它真的让他们变得愚蠢!

    我在我的项目中发现了很多问题,我什至认为这些问题都不是因为那篇文章。没有人发布有关此问题的答案,我并不感到惊讶,因为当您遇到这些类型的问题时,它们对于您正在从事的项目非常个人化并且很难调试。

    我的问题 + 解决方案

    我的问题很常见。当我的场景重新加载时,我一遍又一遍地加载一组资源,在本例中是一个 .sf2(声音字体)文件。老实说,我以为我的所有精灵都解决了这个问题。

    这是我使用 Instruments 找到它的方法:

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

    应该会弹出这个窗口:

    • 点击左上角的red circle 按钮(这将启动您的应用)
    • 在您的应用程序中执行似乎会导致问题的操作,然后按Mark Generation
    • 重复导致问题的操作并继续按Mark Generation
      注意:Mark Generation 拍摄当时应用的快照,以便您查看内存中的变化



    • 停止应用程序运行,然后进入某一代(我选择 C ​​代,因为那时内存使用的差异变得恒定)
    • 显示为SamplerState 的采样器(AVAudioUnitSampler 对象)正在分配大量内存

    • 我点击了SamplerState右边的小箭头,它把我带到了这个视图中(显示了大量分配内存的项目)

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

    • 我双击了我认为会出现问题的方法

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

    • 修复我的代码后,不再有任何主要的内存分配..虽然我还有一些事情要清理!关卡重新加载之间只有 33KB,这要好得多!

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 2013-02-09
      • 2012-12-06
      • 1970-01-01
      相关资源
      最近更新 更多