将我的自定义 Class 存储在 UserDefaults 中,并转换(解析)此 UserDefault 以达到值(Swift 4.2)

Store my custom Class in UserDefaults, and casting(parsing) this UserDefault to reach values (Swift 4.2)

我创建了一个虚拟 IOS 应用程序来很好地解释我的问题。让我分享所有细节:

UserDetail.swift 文件

import Foundation

class UserDetail {
    var accountIsDeleted = false
    var userGUID : String?
    var userAge: Int?
}

LoginPageViewController.swift 文件

import UIKit
class LoginPageViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func loginButtonPressed(_ sender: UIButton) {
        var oUserDetail = UserDetail()
        oUserDetail.accountIsDeleted = true
        oUserDetail.userAge = 38
        oUserDetail.userName = "Dirk Kuyt"

        UserDefaults.standard.set(oUserDetail, forKey: "UserCredentialUserDefaults")
        UserDefaults.standard.synchronize()

        performSegue(withIdentifier: "LoginPage2Homepage", sender: nil)
    }
}

HomepageViewController.swift 文件

import UIKit

class HomepageViewController: UIViewController {

    var result_userGUID = ""
    var result_userAge = 0
    var result_isDeleted = false


    @IBOutlet weak var labelUserGuidOutlet: UILabel!
    @IBOutlet weak var labelAgeOutlet: UILabel!
    @IBOutlet weak var labelAccountIsDeletedOutlet: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setVariablesFromUserDefault()

        labelUserGuidOutlet.text = result_userGUID
        labelAgeOutlet.text = String(result_userAge)
        labelAccountIsDeletedOutlet.text = String(result_isDeleted)
    }

    func setVariablesFromUserDefault()
    {
        if UserDefaults.standard.object(forKey: "UserCredentialUserDefaults") != nil
        {
            // I need a help in this scope
            // I have checked already: My UserDefault exists or not.
            // I need to check type of the value in UserDefault if UserDefault is exists. I need to show print if type of the value in UserDefault is not belongs to my custom class.

            // And then i need to cast UserDefault to reach my custom class's properties: userGUID, userAge, isDeleted
        }
        else
        {
            print("there is no userDefault which is named UserCredentialUserDefaults")
        }
    }
}

我的目的:

  1. 我想将我的自定义 class 示例 (oUserDetail) 存储在 LoginPageViewController 的 UserDefaults 中,并带有登录按钮单击操作。
  2. 我想在主页中检查下面的第一个任务:我的 UserDefault 是否存在(我已经这样做了)
  3. 我想在主页中检查这个作为第二个任务:我的 UserDefault 是否存在。然后检查 UserDefault 值的类型。它是用我的自定义 class 创建的吗?如果不是。打印("value of userdefault is not created with your class")
  4. 第三个任务:如果 UserDefault 是用我的自定义 class 创建的。然后解析该值。设置这 3 个变量:result_userGUIDresult_userAgeresult_isDeleted 以在标签中显示它们。

在登录页面点击登录按钮后出现错误。我不能在 UserDefaults 中存储我的自定义 class 吗?我需要能够存储,因为我在写的时候看到了这个细节:

UserDefaults.standart.set(value: Any?, forKey: String)

我的自定义 class 在上面的 Any 范围内。不是吗?

如果不遵守 NSCoding / Codable 协议

,则无法存储 class 实例
class UserDetail : Codable  {
   var accountIsDeleted:Bool? // you can remove this as it's useless if the you read a nil content from user defaults that means no current account
   var userGUID : String?
   var userAge: Int?
}

店铺

do { 
  let res = try JSONEncoder().encode(yourClassInstance)
  UserDefaults.standard.set(value:res,forKey: "somekey")
}
catch { print(error) }

检索

do {
   if let data =  UserDefaults.standard.data(forKey:"somekey") {
      let res = try JSONDecoder().decode(UserDetail.self,from:data)
   } else {
     print("No account")
   }
}
catch { print(error) }