如何使用 userDefualts 保存打印数组 (swift3)



如何使用userDefualts保存我的数组条目,以确保它们在用户退出应用程序时重新出现。我正在尝试使用 userDefualts 来保存 var numbersWithCreationDate

  import UIKit
    class ViewController: UIViewController {
    @IBOutlet var entry: UILabel!
             var numbersWithCreationDates = [(Int,String)]()
       @IBOutlet var label: UITextField!
        @IBOutlet var scrolView: UIScrollView!

    @IBAction func enterScore(_ sender: Any) {
    if let text = label.text {
        if let number = Int(text){
               // let numberAndDate = (number,Date())
            let date = Date().description
            let numberAndDate = (number, date.substring(to: date.characters.index(of: "+")!))
                numbersWithCreationDates.insert(numberAndDate, at: 0)
                        //line in question
           entry.text = numbersWithCreationDates.map { "($0.0)| ($0.1)" }.joined(separator:"nn")
            UserDefaults.standard.set(numbersWithCreationDates, forKey: "numbersWithCreationDates")
            UserDefaults.standard.synchronize()
            }}
        else {
        entry.text = "Please Enter Number"
        }

letdefaults = UserDefaults.standarddefaults.set(numbersWithCreationDates, forKey: "SavedIntArray"(

        }
                  }
extension Date {
    static var formattedNow: String {
        let now = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
        dateFormatter.timeZone = TimeZone(identifier: "EST")
        return dateFormatter.string(from: now)
    }}

设置标准默认值:

UserDefaults.standard.set(numbersWithCreationDates, forKey: "numbersWithCreationDates")
UserDefaults.standard.synchronize()

您可能需要在字典定义中使用类NSNumber而不是Int(但是,也许不需要,键和变量需要符合 NSCopying 才能保存为默认值(

要检索:

let numbersWithCreationDates = UserDefaults.standard.object(forKey: "numbersWithCreationDates") as! [Int:String]

相关内容

  • 没有找到相关文章

最新更新