微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

UserDefaults 随机不起作用Swift

如何解决UserDefaults 随机不起作用Swift

保存和检索 userDefaults 似乎只能随机工作(突然之间 - 我很确定几天前它可以正常工作!)。

我看不出我的实现有什么问题:

// UtilityFunctions.swift

let defaults = UserDefaults.standard

func saveCurrentGraph(graphName: String) {
    debugPrint("UtilityFunctions--saveCurrentGraph: \(graphName)")
    defaults.set(graphName,forKey: "CurrentGraph")
}

func getSavedGraph() -> String {
    if let savedGraph = defaults.string(forKey: "CurrentGraph") {
        debugPrint("UtilityFunctions--getSavedGraph: \(savedGraph)")
        return savedGraph
    }
    return ""
}

我在不同的地方添加了一些调试语句:

在 AppDelegate.swift 中:

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    debugPrint("----------Launch start (AppDelegate)---------")
    for (key,value) in defaults.dictionaryRepresentation() {
        if key == "CurrentGraph" {
            debugPrint("value retrieved at launch: \(key) = \(value)")
        }
    }
    debugPrint("----------Launch end (AppDelegate)-----------")   
}

在 ViewController.swift 中

var currentGraph = String()

override func viewDidLoad() {
    super.viewDidLoad()
    currentGraph = getSavedGraph()
    debugPrint("value retrieved in viewDidLoad: \(currentGraph)")
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    debugPrint("value retrieved in viewWillAppear: \(currentGraph)")
    createGraphView()
}


func createGraph() {

    debugPrint("=========== createGraph start")
    // save the current graph
    debugPrint("currentGraph = \(currentGraph)")
    saveCurrentGraph(graphName: currentGraph)

    for (key,value) in defaults.dictionaryRepresentation() {
        if key == "CurrentGraph" {
            debugPrint("stored value: \(key) = \(value)")
        }
    }
    debugPrint("=========== createGraph end")

}

以下是一些示例结果:

"----------Launch start (AppDelegate)---------"
"value retrieved at launch: CurrentGraph = John"
"----------Launch end (AppDelegate)-----------"

"UtilityFunctions--getSavedGraph: Betsy"
"value retrieved in viewDidLoad: Betsy"
"UtilityFunctions--getSavedGraph: Betsy"
"value retrieved in viewWillAppear: Betsy"

"=========== createGraph start"
"currentGraph = Betsy"
"UtilityFunctions--saveCurrentGraph: Betsy"
"stored value: CurrentGraph = John"
"=========== createGraph end"

我可以看到在 AppDelegate 中读取 userDefaults 字典时存储了正确的值。

但是,当我调用 getSavedGraph 方法时,它返回一个旧值。

当我在 createGraph 方法中保存一个新值时,它似乎没问题,但再次读回 userDefaults 字典时,会显示启动时读取的第一个值。

我做错了吗???

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。