简体   繁体   English

在特定时间从 UserDefaults 中删除保存的数据?

[英]Delete saved data form UserDefaults at a specific time?

I'm using UserDefaults with SwiftUI to save my data from multiple variables and I use them for graphs which shows some daily information.我在 SwiftUI 中使用 UserDefaults 来保存来自多个变量的数据,并将它们用于显示一些日常信息的图表。 Is there a way to delete or reset the saved data form UserDefaults to only contain the data form the current day?有没有办法删除或重置保存的数据表单 UserDefaults 以仅包含当天的数据表单? For example delete the data at 23:59 every night.比如每晚23:59删除数据。

@Published var waterGraph: Float = UserDefaults.standard.float(forKey: "waterGraph") {
        didSet {
            UserDefaults.standard.set(self.waterGraph, forKey: "waterGraph")
        }
    }

Do you really need to delete the data from your UserDefaults at exactly 23:59?您真的需要在恰好 23:59 从您的 UserDefaults 中删除数据吗? If you do then you would have to run background tasks which can be quite complicated.如果这样做,则必须运行可能非常复杂的后台任务。 Another easier alternative is to clear the UserDefaults each time the user opens the app and if it has been 24 hours since your UserDefaults data was stored.另一个更简单的替代方法是在用户每次打开应用程序时清除 UserDefaults,如果您的 UserDefaults 数据已存储 24 小时。 Store a value in your UserDefaults called "in24hours" and set its value to 24 hours from the current time.在您的 UserDefaults 中存储一个名为“in24hours”的值,并将其值设置为距当前时间 24 小时。 In the appDelegate's didFinishLaunchingWithOptions function, check for the date stored in the userDefaults "in24hours" and if the current time is greater than the time in that variable, then you can clear your userDefaults there.在 appDelegate 的 didFinishLaunchingWithOptions 函数中,检查存储在 userDefaults“in24hours”中的日期,如果当前时间大于该变量中的时间,那么您可以在那里清除 userDefaults。 You can set the "in24hours" variable whenever you want (after you add your to be deleted data in UserDefaults).您可以随时设置“in24hours”变量(在 UserDefaults 中添加要删除的数据后)。 Instead of setting the "in24Hours" to 24 hours from the current time and date, you could also set it to midnight on the following date.除了将“in24Hours”设置为当前时间和日期的 24 小时之外,您还可以将其设置为下一个日期的午夜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM