Last active
May 1, 2022 17:32
-
-
Save andresr-dev/f9d7383d178c511deaab9282eaee3611 to your computer and use it in GitHub Desktop.
This is an example of how to use UserDefaults inside a ViewModel. We should not store more than 500KB of data in UserDefaults
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct Card: Identifiable, Codable { | |
var id = UUID() | |
let prompt: String | |
let answer: String | |
} | |
@MainActor class ViewModel: ObservableObject { | |
@Published var cards = [Card]() | |
init() { | |
loadData() | |
} | |
func loadData() { | |
if let data = UserDefaults.standard.data(forKey: "Cards") { | |
if let decoded = try? JSONDecoder().decode([Card].self, from: data) { | |
cards = decoded | |
} | |
} | |
} | |
func saveData() { | |
if let data = try? JSONEncoder().encode(cards) { | |
UserDefaults.standard.set(data, forKey: "Cards") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment