iOS开发:SKScene View Controller退出未销毁引发音效及FPS问题求助
Hey there! You’re spot-on with your diagnosis—your SKScene’s view controller isn’t getting properly cleaned up when you exit via the modal segue, which is why the audio keeps playing and FPS tanks after multiple game launches. Let’s fix this with a clear, step-by-step Objective-C solution:
Step 1: Clean Up Audio & Scene When the View Disappears
Add this code to your game’s view controller (the one holding the SKView/SKScene) to halt all audio and properly tear down the scene when the view is about to disappear:
- (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // Pause the SKView to stop rendering and updates SKView *skView = (SKView *)self.view; skView.paused = YES; // If you have a reference to your SKScene, clean it up if (self.gameScene) { // Stop all running actions in the scene [self.gameScene removeAllActions]; [SKAction stopAllActions]; // Stop any background audio (adjust based on your audio setup) // Example for AVAudioPlayer: if (self.backgroundMusicPlayer) { [self.backgroundMusicPlayer stop]; self.backgroundMusicPlayer = nil; } // Remove the scene from the SKView and nil out the reference [skView presentScene:nil]; self.gameScene = nil; } }
Step 2: Fix Circular References in Your SKScene
If your SKScene uses blocks (like timers or repeating actions), make sure you’re using a weak reference to self to avoid circular references that prevent the scene/controller from being deallocated:
// Inside your SKScene implementation __weak typeof(self) weakSelf = self; [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[ [SKAction runBlock:^{ [weakSelf updateGameLogic]; // Use weakSelf instead of self }], [SKAction waitForDuration:1.0] ]]]];
Step 3: Verify Proper Deallocation
Add a dealloc method to your game view controller to confirm it’s being released when you exit the game. You should see this log in Xcode’s console if everything works:
- (void)dealloc { NSLog(@"GameViewController successfully deallocated!"); }
Step 4: Ensure Correct Segue Dismissal
When triggering the exit from your game, make sure you’re using the standard modal dismissal method to trigger the viewWillDisappear lifecycle hook:
// In your exit button's action method - (IBAction)exitGameButtonTapped:(id)sender { [self dismissViewControllerAnimated:YES completion:nil]; }
By following these steps, your SKScene and its view controller will be properly cleaned up, stopping audio immediately and preventing FPS drops from accumulated unused instances.
内容的提问来源于stack exchange,提问作者L. Richmond

