Demonstrates a memory leak bug SwiftUI's toolbar APIs exhibit on macOS

Overview

Mac SwiftUI Toolbar Memory Leak Demo

On Big Sur (macOS 11), SwiftUI's APIs for adding toolbar items to a window have (at least) two bugs around view recreation that lead to memory leaks and increased CPU pressure over time. Monterey (macOS 12) appears to not have these bugs.

Issue #1: ToolbarItem always creates an additional, "ghost" copy of the view it contains

For example,

Color.clear
    .toolbar {
        ToolbarItem {
            Color.red
                .onAppear { print("This will be printed twice.") }
        }
    }

will print "This will be printed twice" twice. ToolbarItem creates an additional copy of Color.red. This ghost copy is fully functional, reacts to state changes (assuming it hosts something within itself that changes state), and is not destroyed until its parent .toolbar() leaves the view hierarchy. This is true even if your view hierarchy is complete static, with nothing to trigger a state change.

Issue #2: ToolbarItem creates an additional ghost copy of the view it contains every single time state changes

Pretend you have some state:

@State var counter = 0

...and a toolbar item in your view, that updates that state whenever every so often:

Color.clear
    .toolbar {
        ToolbarItem {
            Text("\(counter)")
                .onAppear { print("This will be printed every change of counter.") }
        }
    }
    .onAppear {
        //  Start a timer that updates counter += 1 every so often
    }

that onAppear() will be printed every single time counter changes. The same issues outlined in the previous issue are true here.

Closing

Both of these issues are demonstrated in the sample project in this repo.

I've filed this bug under FB9453009.

You might also like...
Navigation toolbar is a Swift slide-modeled UI navigation controller.
Navigation toolbar is a Swift slide-modeled UI navigation controller.

Navigation toolbar is a Swift slide-modeled UI navigation controller. We specialize in the designing and coding of custom UI for Mo

Advanced Catalyst Example with sidebar, list view, SwiftUI detail view, toolbar & AppKit bundle
Advanced Catalyst Example with sidebar, list view, SwiftUI detail view, toolbar & AppKit bundle

Advanced Catalyst Example This is an example of a Catalyst app using a three-column layout, with a primary toolbar. It includes topics such as: Drag &

Demonstrate the toolbar view modifier for SwiftUI with different placements
Demonstrate the toolbar view modifier for SwiftUI with different placements

ToolbarProject Demonstrate the toolbar view modifier for SwiftUI with different placements Youtube tutorial -- https://youtu.be/jTW5Z-kyL8g Use toolb

This is a simple Mac Catalyst example showcasing how to build a dropdown menu toolbar button using AppKit.
This is a simple Mac Catalyst example showcasing how to build a dropdown menu toolbar button using AppKit.

CatalystToolbarMenuButton This is a simple Mac Catalyst example showcasing how to build a dropdown menu toolbar button using AppKit. There are ways to

A sample app demonstrates how to use Atlantis on Swift Playground (iOS/macOS)
A sample app demonstrates how to use Atlantis on Swift Playground (iOS/macOS)

Atlantis with Swift Playground A sample app demonstrates how to use Atlantis on

MacOS scrollview nsview scrollbar bug demo

macOS SwiftUI ScrollView Scrollbar Bug Demo If you create a ScrollView that contains an NSView that intersects the scroll view's scrollbars, the scrol

A longstanding annoying bug in our beloved operating system macOS

Houston There is a longstanding annoying bug in our beloved operating system macOS. If you open an application while Mission Control is active, the ap

Demonstrates how to build a live broadcast app(Swift 3)
Demonstrates how to build a live broadcast app(Swift 3)

This project is to demonstrate how to build a live broadcast app. It include these features: Create a room to broadcast your live stream Join a room t

Sample iOS AR app that demonstrates how to capture the texture of a user's face in realtime.
Sample iOS AR app that demonstrates how to capture the texture of a user's face in realtime.

Sample iOS AR app that demonstrates how to capture the texture of a user's face in realtime. This texture can be used to create a simple textured 3D face model.

Demonstrates hosting SwiftUI in a UISplitViewController to gain the sidebar style in Mac Catalyst
Demonstrates hosting SwiftUI in a UISplitViewController to gain the sidebar style in Mac Catalyst

Really trivial example showing how to wrap SwiftUI in a UISplitViewController, so that you can use the correct sidebar background style when building for macOS.

The demo app demonstrates a real-time application using FindSurface to search point clouds, which ARKit provides, for geometry shapes.
The demo app demonstrates a real-time application using FindSurface to search point clouds, which ARKit provides, for geometry shapes.

FindSurface-GUIDemo-iOS (Swift) CurvSurf FindSurface™ GUIDemo for iOS (Swift) Overview This demo app demonstrates a real-time application using FindSu

Swift Xcode Project that demonstrates how to set up a microphone input via AudioKit verions 5.

AudioKit Mic Input Swift Xcode Project that demonstrates how to set up a microphone input via AudioKit verions 5. Be sure to plug in headphones in ord

A repository that demonstrates the difficulty to run async tests with Xcode 13.2 beta on pre iOS-15 simulators

A repository that demonstrates the difficulty to run async tests with Xcode 13.2 beta on pre iOS-15 simulators This demonstration uses an iOS 13.7 sim

The app demonstrates how to use Firebase in a SwiftUI iOS app

Firebase SwiftUIDemo app This app demonstrates how to use Firebase in a SwiftUI iOS app. Firebase Setup Go to firebase.com Click new project. Copy app

Demonstrates how to integrate Stripe Subscriptions on iOS

Stripe Subscriptions with iOS This example app demonstrates how to integrate Stripe subscriptions with the prebuilt payment UI Requirements Create an

A demo demonstrates how to use combine and MVVM in the SwiftUI app
A demo demonstrates how to use combine and MVVM in the SwiftUI app

SwiftUI-MVVM-Combine A demo demonstrates how to use combine and MVVM in the Swif

This app demonstrates how to use the Google Cloud Speech API and Apple on-device Speech library to recognize speech in live recorded audio.

SpeechRecognitionIOS This app demonstrates how to use Google Cloud Speech API and Apple on-device Speech library to recognize speech in live audio rec

GraphQL-GitHub-Reader - Simple sample project that demonstrates how to connect with GitHub's API using GraphQL + Apollo
GraphQL-GitHub-Reader - Simple sample project that demonstrates how to connect with GitHub's API using GraphQL + Apollo

GHPViewer A beatiful way to see your GitHub Profile Installation The project is splitted in two folders: GHPViewer: Contains the iOS Application relat

Todo is an iOS App written in Swift. This app is used for an online video training course. This app demonstrates how to use UITableViewController.
Todo is an iOS App written in Swift. This app is used for an online video training course. This app demonstrates how to use UITableViewController.

Todo Todo is an iOS App written in Swift. This app is used for an online video training course. This app demonstrates how to use UITableViewController

Comments
  • I noticed there is no leak if you use a binding in the ToolbarItem

    I noticed there is no leak if you use a binding in the ToolbarItem

    struct ViewDemonstratingViewRecreation: View {
        
        @State var someState = 0
        
        var body: some View {
            Color.blue
                .toolbar {
                    ToolbarItem {
                        ViewDemonstratingViewRecreation2(someState:$someState)
                            .onAppear {
                                print("You should see this message printed many times.")
                            }
                    }
                }
                .onAppear {
                    Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) {
                        _ in
                        someState += 100
                    }
                }
        }
        
    }
    
    struct ViewDemonstratingViewRecreation2: View {
        
        @Binding var someState: Int
        
        var body: some View {
            Text("\(someState)")
                .onAppear {
                    print("You should see this message printed many times.")
                }
        }
    }
    
    
    opened by malhal 2
Owner
Matt Curtis
Software & Web Developer. I made Fluid for Sketch and Hyphen Reader for iOS.
Matt Curtis
Automaticly display Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder and etc with one line of code based on Swift. Just like God opened his eyes

GodEye Automaticly display Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder and etc with one line of code based on Swift. Just like God opened hi

陈奕龙(子循) 3.7k Dec 23, 2022
Free macOS app for iOS view debugging.

Introduction You can inspect and modify views in iOS app via Lookin, just like UI Inspector in Xcode, or another app called Reveal. Official Website:h

Li Kai 575 Dec 28, 2022
Xray is viewDebugging tool for iOS, tvOS, watchOS and macOS

XRay XRay is view debugging tool for iOS. Currently, XRay can show all of the view hierarchies in UIKit. For SwiftUI, I'm working on it. XRay helps yo

Shawn Baek 10 Jun 10, 2022
Awesome autolayout Toolbar. Toolbar is a library for iOS. You can easily create chat InputBar.

Toolbar This toolbar is made with Autolayout. It works more interactively than UIToolbar. Please Donate Slow Animations Debug mode If you want a Toolb

1amageek 459 Sep 16, 2022
Memory leak when CoreML ML Program is runing on GPU

MLProgramMemoryLeak Every layer running on the GPU in ML Program will leak 912 bytes by MPSGraphEngine. This can easily lead to 200KB+ memory leak eve

Yi Xie 2 Jun 17, 2022
Profiling / Debugging assist tools for iOS. (Memory Leak, OOM, ANR, Hard Stalling, Network, OpenGL, Time Profile ...)

MTHawkeye Readme 中文版本 MTHawkeye is profiling, debugging tools for iOS used in Meitu. It's designed to help iOS developers improve development producti

meitu 1.4k Dec 29, 2022
Matthew Asaminew 0 Jan 25, 2022
A zero-code template app that demonstrates how to use TheraForge's APIs and can be used for fast prototyping

TheraForge MagicBox 1.0.0-beta The Open TheraForge (OTF) MagicBox app is a template for creating digital health solutions that help people better mana

TheraForge 0 Dec 23, 2021
Automaticly display Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder and etc with one line of code based on Swift. Just like God opened his eyes

GodEye Automaticly display Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder and etc with one line of code based on Swift. Just like God opened hi

陈奕龙(子循) 3.7k Dec 23, 2022
🎀 A simple cross-platform toolbar/custom input accessory view library for iOS & macOS.

Ribbon ?? A simple cross-platform toolbar/custom input accessory view library for iOS & macOS. Written in Swift. Looking for... A type-safe, XPC-avail

Chris Zielinski 294 Nov 28, 2022