1

我有一个 Published 变量,该变量在调用函数时会发生变化。我在类中打印变量,我可以看到它已经设置了变量,但是当它没有改变我的视图时,当我打印变量时,它只打印我最初设置变量的内容。

我知道在这方面有几个类似的帖子,但是在浏览完它们之后,我仍然不确定我做错了什么。

代码如下:(减去我认为在这里不相关的位)

包含被调用以更改变量的函数的类

class MusicManager: NSObject, ObservableObject {

    @Published var playlistLabel: String = "N/A"

    func playPlaylistNow(chosenPlaylist: String?) {
        ...
        playlistLabel = chosenPlaylist!
        print(playlistLabel) // I get the revised variable printed here 
    }
}

查看更新

struct HomeView: View {

    ...
    @ObservedObject var musicManager: MusicManager = MusicManager()

    var body: some View {
                ...
                SongLabels(trackLabel: currentTrack!, artistLabel: currentArtist!, playlistLabel: musicManager.playlistLabel)
                ...
            }
                ...
            .onAppear {
                self.updateTrackData()
        }
    }

    func updateTrackData() {
        print("Playlist: \(musicManager.playlistLabel)") // I get the original "N/A" printed here
    }

调用函数的视图:

{
    @State private var showingAlert = false
    let musicManager: MusicManager = MusicManager()
    var playlistName: String
    var body: some View {
        Button(action: {
            self.showingAlert = true
            self.musicManager.playPlaylistNext(chosenPlaylist: self.playlistName)
        }) {
            Text("Play Next")
        }
        .alert(isPresented: $showingAlert) {
            ...
        }
        ...
    }
}
4

1 回答 1

-1

您的应用中有多个实例MusicManager,因此它们并不相同。

如果你想打印,你可以打印两个musicManager,看看有什么区别。

于 2019-12-10T21:34:43.123 回答