CodexBloom - Programming Q&A Platform

SwiftUI macOS app crashing with NSApplication on multiple monitors due to window placement

👀 Views: 80 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
swiftui macos nsapplication Swift

I'm collaborating on a project where I've searched everywhere and can't find a clear answer. Quick question that's been bugging me - I'm working with a crash in my SwiftUI macOS application when trying to open a new window on a secondary monitor. The app seems to work fine when using just the primary monitor, but when I attempt to position the new window on the second display, it crashes with the following behavior: ``` Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000 ``` I've also noticed that this happens only when the app is in a certain state, specifically after a modal view is dismissed. Below is the relevant code snippet where I create and show the new window: ```swift struct ContentView: View { var body: some View { Button(action: { openNewWindow() }) { Text("Open New Window") } } func openNewWindow() { let newWindowController = NSWindowController(windowNibName: "NewWindow") newWindowController.showWindow(nil) if let screen = NSScreen.screens.last { newWindowController.window?.frame.origin = screen.frame.origin } } } ``` I've tried different approaches for setting the window's frame, ensuring that the window is fully initialized before moving it, and even checking that all components are compliant with `@State` and `@Binding`. Despite these efforts, the crash continues. Has anyone else faced similar issues when handling multiple displays in a SwiftUI macOS app? What might I be missing? This is part of a larger API I'm building. I'd really appreciate any guidance on this. Could someone point me to the right documentation?