Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

swift - SwiftUI: Encode a struct to be saved in AppStorage

Currently trying to build my first app in swiftUI. The part I thought would be the easiest as become a nightmare... save a struct in AppStorage to be available upon restart of the app

I got two struct to save. The first is for player and I have implemented the RawRepresentable

struct Player: Codable, Identifiable {
    let id: Int
    let name: String
    let gamePlayed: Int
    let bestScore: Int
    let nbrGameWon: Int
    let nbrGameLost: Int
    let totalScore: Int?

}

typealias PlayerList = [Player]
extension PlayerList: RawRepresentable {
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
            let result = try? JSONDecoder().decode(PlayerList.self, from: data)
        else {
            return nil
        }
        self = result
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
            let result = String(data: data, encoding: .utf8)
        else {
            return "[]"
        }
        return result
    }
}

Calling in my view this way:

struct AddPlayerView: View {
    @State var name: String = ""
    @State var isDisabled: Bool = false
    @State var modified: Bool = false
    @AppStorage("players") var players: PlayerList = PlayerList()
    ...
}

The above works, now I also want to save the current game data, I have the following struct:

struct Game: Codable, Identifiable {
    var id: Int
    var currentPlayerIndexes: Int
    var currentRoundIndex: Int?
    var dealerIndex: Int?
    var maxRounds: Int?
    var dealResults: [Int: Array<PlayerRoundSelection>]?
    var currentLeaderIds: Array<Int>?
    var isGameInProgress: Bool?
}

extension Game: RawRepresentable {
    public init?(rawValue: String) {
        if rawValue == "" {
            // did to fix issue when calling AppStorage, but it is probably a bad idea
            self = Game(id:1, currentPlayerIndexes:1)
        }
        else {
            guard let data = rawValue.data(using: .utf8),
                let result = try? JSONDecoder().decode(Game.self, from: data)
            else {
                return nil
            }
            self = result
        }
    }

    public var rawValue: String {
        guard let data = try? JSONEncoder().encode(self),
            let result = String(data: data, encoding: .utf8)
        else {
            return ""
        }
        return result
    }
}

As soon as I try to modify the struct, it calls rawValue and the encoding fails with the following:

error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated

error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x7ffee49bbff8).

Here part of the code that access the struct:

struct SelectPlayersView: View {
    @AppStorage("currentGame") var currentGame: Game = Game(rawValue: "")!
    ....
NavigationLink(
                    destination: SelectModeTypeView(), tag: 2, selection: self.$selection) {
                    ActionButtonView(text:"Next", disabled: self.$isDisabled, buttonAction: {
                        var currentPlayers = Array<Int>()
                        self.players.forEach({ player in
                            if selectedPlayers.contains(player.id) {
                                currentPlayers.insert(player.id, at: currentPlayers.count)
                            }
                        })
    // This used to be a list of indexes, but for testing only using a single index
    self.currentGame.currentPlayerIndexes = 6
                        self.selection = 2
                    })
...

I found the code to encode here: https://lostmoa.com/blog/SaveCustomCodableTypesInAppStorageOrSceneStorage/

My understanding is that with the self in the encode, it generate an infinite loop hence the bad access.

I have really no knowledge how to properly encode this, any help, links would be appreciated


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...