gpt4 book ai didi

ios - 如何保存结构体的顺序?

转载 作者:行者123 更新时间:2023-11-30 11:56:45 25 4
gpt4 key购买 nike

我创建了一个应用程序,它随机显示数组中的不同字符串。为了确保没有数组重复,我创建了一个结构,它只显示尚未显示的字符串。

效果很好,但我的问题是,一旦我切换场景,结构就会重置,尽管我尝试将其保存为用户默认值。有人知道当我尝试应用 UserDefaults 时我在哪里犯了错误吗?

这是我的包含保存方法的结构:

 struct RandomItems: Codable
{
var items : [String]
var seen = 0

init(items:[String], seen: Int)
{
self.items = items
self.seen = seen
}
init(_ items:[String])
{ self.init(items: items, seen: 0) }

mutating func next() -> String
{
let index = Int(arc4random_uniform(UInt32(items.count - seen)))
let item = items.remove(at:index)
items.append(item)
seen = (seen + 1) % items.count
return item
}
func toPropertyList() -> [String: Any] {
return [
"items": items,
"seen": seen]
}
}
override func viewDidLoad() {
let defaults = UserDefaults.standard
if let quotes = defaults.codable(RandomItems.self, forKey: "quotes") as? RandomItems {
self.quotes = quotes
}
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector:Selector(("saveData:")), name: Notification.Name.UIApplicationWillTerminate, object:nil)
}
func storeQuotes() {
// Code to save struct
let defaults = UserDefaults.standard
if let quotes = quotes {
defaults.set(codable: quotes, forKey: "quotes")
}
}
override func viewDidAppear(_ animated: Bool) {
// Code to load the struct again after the view appears.

}

override func viewWillDisappear(_ animated: Bool) {

storeQuotes()
}
func saveData(notification: Notification) {
// Save your data here when app is closed
print("Saving data...")
storeQuotes()
}

}

extension UserDefaults {

func set<T: Encodable>(codable: T, forKey key: String) {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(codable)
let jsonString = String(data: data, encoding: .utf8)!
print("Saving \"\(key)\": \(jsonString)")
self.set(jsonString, forKey: key)
} catch {
print("Saving \"\(key)\" failed: \(error)")
}
}
func codable<T: Decodable>(_ codable: T.Type, forKey key: String) -> T? {
guard let jsonString = self.string(forKey: key) else { return nil }
guard let data = jsonString.data(using: .utf8) else { return nil }
let decoder = JSONDecoder()
print("Loading \"\(key)\": \(jsonString)")
return try? decoder.decode(codable, from: data)
}

最佳答案

如果 UserDefaults 中已经存储了值,则可以检查 viewDidLoad,并且可以删除 viewDidAppear 中的代码:

override func viewDidLoad() {
let defaults = UserDefaults.standard
if let quotes = defaults.codable(RandomItems.self, forKey: "quotes") as? RandomItems {
self.quotes = quotes
}
}

编辑:

如果您想在应用程序移至后台时存储您的报价:

在viewWillAppear中添加通知观察者:

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(saveData), name: Notification.Name.UIApplicationDidEnterBackground, object:nil)
}

func storeQuotes() {
// Code to save struct
let defaults = UserDefaults.standard
if let quotes = quotes {
defaults.set(codable: quotes, forKey: "quotes")
}
}

override func viewWillDisappear(_ animated: Bool) {
// Code to save struct before the view disappears.
storeQuotes()
}

func saveData() {
// Save your data here when app is closed
print("Saving data...")
storeQuotes()
}

关于ios - 如何保存结构体的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47727927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com