AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79166123
Accepted
Manngo
Manngo
Asked: 2024-11-07 18:58:15 +0800 CST2024-11-07 18:58:15 +0800 CST 2024-11-07 18:58:15 +0800 CST

Usando SwiftData com um MenuExtra

  • 772

Tenho um script que adicionará a um armazenamento SwiftData se os dados ainda não existirem. Tenho a lógica funcionando, para uma janela comum, mas não consigo fazê-la funcionar em um Menu Extra. Aqui está um exemplo:

import SwiftUI
import SwiftData

@main
struct XBApp: App {
    var bundleID: String = "whatever"

    
    var body: some Scene {
        MenuBarExtra("Something", systemImage: "questionmark.bubble") {
//      WindowGroup {
            VStack {
                XBContent(bundleID: bundleID)
                    .padding(0)
            }
            .modelContainer(for: XBData.self)
        }
    }
}

@Model
class XBData {
    @Attribute(.unique) var bundle: String
    var note: String
    
    init(bundle: String, note: String = "Note") {
        self.bundle = bundle
        self.note = note
    }
}

struct XBList: View {
    @Query(sort: \XBData.bundle, animation: .easeInOut) var allXBarData: [XBData]
    @Environment(\.modelContext) private var modelContext
    
    var body: some View {
        VStack {
            Text("Everything So Far …")
            List {
                ForEach(allXBarData) { xbd in
                    HStack {
                        Text(xbd.bundle)
                        Spacer()
                        Text(xbd.note)
                        Spacer()
                        Button("", systemImage: "trash", action: {
                            modelContext.delete(xbd)
                        })
                        .buttonStyle(.bordered)
                    }
                }
            }
        }
        .modelContainer(for: XBData.self)
    }
}

struct XBContent: View {
    var bundleID: String = ""
    @Environment(\.modelContext) private var modelContext
    @State var xBData: XBData?
    @Query(sort: \XBData.bundle, animation: .easeInOut) var allXBarData: [XBData]

    func loadData(bundleID: String) -> XBData? {
        print("\(#fileID):\(#line) - \(bundleID)")
//      let filter = FetchDescriptor<XBData>(predicate: #Predicate { $0.bundle == bundleID })
        let filter = FetchDescriptor<XBData>(predicate: #Predicate { $0.bundle == bundleID })
        do {
            var xbd = try modelContext.fetch(filter).first
            print("\(#fileID):\(#line) - \(xbd == nil)")
            if xbd == nil {
                print("\(#fileID):\(#line) - \(xbd!.note)")
                xbd = XBData(bundle: bundleID, note: "Newish Note: \(bundleID)")
                modelContext.insert(xbd!)
                try modelContext.save()
            }
            else {
                print("\(#fileID):\(#line) - \(xbd!.note)")
            }
            return xbd
        } catch {
            print("\(#line) oops")
            return nil
        }
    }
    
    init(bundleID: String) {
        self.bundleID = bundleID
    }
    
    var body: some View {
        VStack {
            Text(bundleID)
//          XBList()
            List {
                ForEach(allXBarData) { xbd in
                    HStack {
                        Text(xbd.bundle)
                        Spacer()
                        Text(xbd.note)
                        Spacer()
                        Button("", systemImage: "trash", action: {
                            modelContext.delete(xbd)
                        })
                        .buttonStyle(.bordered)
                    }
                }
            }
        }
        .modelContainer(for: XBData.self)
        .onAppear {
            xBData = loadData(bundleID: bundleID)!
            xBData!.note = "Newish Note: \(bundleID)"
            try? modelContext.save()
        }
    }
}

Desculpe pelo tamanho da amostra.

Presumindo que um item com id de whatevernão existe, ele deve ser adicionado e exibido na lista.

Na estrutura App, comentei o WindowGroup. Se eu alternar para isso e não para o MenuBarExtra, funciona como esperado.

Também recebo a mensagem muito útil:

Não é possível encontrar ou decodificar os motivos
Falha ao obter ou decodificar os motivos indisponíveis

No entanto, isso acontece com o WindowGroup ou o MenuBarExtra, então não sei se está relacionado.

Qual é o truque para fazer isso funcionar com um MenuBarExtra?

macos
  • 1 1 respostas
  • 49 Views

1 respostas

  • Voted
  1. Best Answer
    workingdog support Ukraine
    2024-11-08T07:59:56+08:002024-11-08T07:59:56+08:00

    Experimente esta abordagem para usarMenuBarExtra

     @main
     struct XBApp: App {
         var bundleID: String = "whatever"
         
         var body: some Scene {
             MenuBarExtra("Something", systemImage: "questionmark.bubble") {
                 VStack {
                     XBContent(bundleID: bundleID)
                 }
             }
             .modelContainer(for: XBData.self)  // <--- here
             .menuBarExtraStyle(.window)
         }
     }
     
    

    Observe que func loadDatanão use !em seu código, especialmente em if xbd == nil { print("\(#fileID):\(#line) - \(xbd!.note)") ...

    Observe também: pare de usar .modelContainer(for: XBData.self) em todos os lugares, apenas um em você XBAppjá é suficiente.

    Observe que, quando você faz isso modelContext.insert(xbd!), saveos dados são automaticamente salvos, você não precisa usartry modelContext.save()

    EDITAR-1

    Este é o código completo que funciona muito bem para mim, testado no macOS 15.

    import SwiftUI
    import SwiftData
    
    @main
    struct XBApp: App {
        var bundleID: String = "whatever"
        
        var body: some Scene {
            MenuBarExtra("Something", systemImage: "questionmark.bubble") {
                VStack {
                    XBContent(bundleID: bundleID)
                }
            }
            .modelContainer(for: XBData.self)  // <--- here
            .menuBarExtraStyle(.window)
        }
    }
    
    struct XBList: View {
        @Environment(\.modelContext) private var modelContext
        @Query(sort: \XBData.bundle, animation: .easeInOut) var allXBarData: [XBData]
        
        
        var body: some View {
            VStack {
                Text("Everything So Far …")
                List {
                    ForEach(allXBarData) { xbd in
                        HStack {
                            Text(xbd.bundle)
                            Spacer()
                            Text(xbd.note)
                            Spacer()
                            Button("", systemImage: "trash", action: {
                                modelContext.delete(xbd)
                            })
                            .buttonStyle(.bordered)
                        }
                    }
                }
            }
        }
    }
    
    struct XBContent: View {
        var bundleID: String = ""
        
        @Environment(\.modelContext) private var modelContext
        
        @State private var xBData: XBData?
        
        @Query(sort: \XBData.bundle, animation: .easeInOut) var allXBarData: [XBData]
        
        func loadData(bundleID: String) -> XBData? {
            print("\(#fileID):\(#line) - \(bundleID)")
            let filter = FetchDescriptor<XBData>(predicate: #Predicate { $0.bundle == bundleID })
            do {
                var xbd = try modelContext.fetch(filter).first
                print("\(#fileID):\(#line) ---> xbd is nil \(xbd == nil)")
                if xbd == nil {
                    xbd = XBData(bundle: bundleID, note: "A Newish Note: \(bundleID)")
                    modelContext.insert(xbd!)
                    // try modelContext.save()
                    print("\(#fileID):\(#line) ---> \(xbd!.note)")
                }
                else {
                    print("\(#fileID):\(#line) - \(xbd!.note)")
                }
                return xbd
            } catch {
                print("\(#line) oops")
                return nil
            }
        }
        
        var body: some View {
            VStack {
                
                // for testing, adding some test XBData
                Button(action: {
                    let randm = String(UUID().uuidString.prefix(5))
                    let newItem = XBData(bundle: randm, note: randm)
                    modelContext.insert(newItem)
                }) {
                    Label("Add Item", systemImage: "plus")
                }.buttonStyle(.bordered)
                    .padding(10)
                
                Text(bundleID)
                
                XBList()
                
            }
            .onAppear {
                if let xb = loadData(bundleID: bundleID) {
                    xBData = xb
                    xBData!.note = "B Newish Note: \(bundleID)"
                    print("\(#fileID):\(#line) ---> \(xBData!.note)")
                    //try? modelContext.save()
                }
            }
        }
    }
    
    #Preview {
        XBContent(bundleID: "whatever")
            .modelContainer(for: XBData.self, inMemory: true)
    }
    
    @Model
    class XBData {
        @Attribute(.unique) var bundle: String
        var note: String
        
        init(bundle: String, note: String = "Note") {
            self.bundle = bundle
            self.note = note
        }
    }
    
    • 0

relate perguntas

  • Retornando uma data para o primeiro dia do mês

  • Por que o VS Code está me obrigando a usar “opção + clique” para abrir links do editor em vez de “cmd + clique” no macOS?

  • Código do Visual Studio aguardando a segunda tonalidade do acorde. (Ctrl+G)

  • AppKit lendo entrada do teclado em thread separado

  • MAC e ZSH - Exportar não "grudar" [fechado]

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve