ObservedObject未收到变量更改

时间:2019-12-10 16:52:26

标签: swiftui observedobject

我有一个Published变量,该变量在调用函数时会更改。我在类中打印了变量,我可以看到它已经设置了变量,但是当它没有更改View时,并且当我打印变量时,它只打印了我最初设置变量的位置。

我知道也有一些类似的帖子,但是经过它们之后,我仍然不确定自己在做什么错。

代码如下:(我认为这里与负号无关)

包含用于更改变量的函数的类

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) {
            ...
        }
        ...
    }
}

1 个答案:

答案 0 :(得分:0)

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

如果要打印,可以同时打印musicManager,以查看区别。