CodexBloom - Programming Q&A Platform

Unexpected Memory Leak When Using AVPlayer in macOS 14 with Swift - how to to Release Resources

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-08-30
macos avplayer memory-leak swift Swift

I'm getting frustrated with I've been struggling with this for a few days now and could really use some help. I'm experiencing a memory leak in my macOS 14 application when using `AVPlayer` to play video content. I have set up an `AVPlayer` instance, but despite stopping playback and attempting to deallocate the player, I notice that memory usage continues to grow, indicating that resources are not being released properly. Here's a simplified version of the code I'm using: ```swift import Cocoa import AVFoundation class VideoPlayerController: NSViewController { var player: AVPlayer? var playerLayer: AVPlayerLayer? override func viewDidLoad() { super.viewDidLoad() setupPlayer() } func setupPlayer() { guard let url = URL(string: "https://example.com/video.mp4") else { return } player = AVPlayer(url: url) playerLayer = AVPlayerLayer(player: player) playerLayer?.frame = view.bounds if let playerLayer = playerLayer { view.layer?.addSublayer(playerLayer) } player?.play() } func stopPlayback() { player?.pause() player = nil // Attempting to release resources playerLayer?.removeFromSuperlayer() playerLayer = nil } } ``` I call `stopPlayback()` when the user navigates away from the video player, but the app continues to consume excessive memory. I've tried manually setting the `player` and `playerLayer` to `nil` and calling `removeFromSuperlayer()`, yet Instruments shows that `AVPlayer` instances are being retained longer than expected. Additionally, I checked for any strong references or retain cycles by using the memory graph debugger, but everything seems normal. Is there a specific best practice or additional step I’m missing to properly release the `AVPlayer` resources? Any insights or alternative approaches would be greatly appreciated! Any ideas what could be causing this? I'm working on a application that needs to handle this. Thanks in advance! How would you solve this? I'm coming from a different tech stack and learning Swift.