Swift: 用UserDefaults保存自定义类(customer class)

杜英范
2023-12-01

Swift: 用UserDefaults保存自定义类(customer class)

话不多说,直接把最简单,容易理解的代码呈上。

如何用UserDefaults保存customer Class

这里我直接用Class作为要保存的类。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let classData1 = Class(className: "a", roomName: "b", cellNumber: 1)
        let classData2 = Class(className: "c", roomName: "d", cellNumber: 2)
        let classData3 = Class(className: "e", roomName: "f", cellNumber: 3)
        let classArray = [classData1, classData2, classData3]

        // 保存
        UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: classArray), forKey: "TimeTable")
        UserDefaults.standard.synchronize()

        // 取得
        if let data = UserDefaults.standard.object(forKey: "TimeTable") as? Data,
            let classArray = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Class] {
            print(classArray)
        }
    }
}

class Class: NSObject, NSCoding {

    let className: String
    let roomName: String
    let cellNumber: Int

    init(className: String, roomName: String, cellNumber: Int) {

        self.className = className
        self.roomName = roomName
        self.cellNumber = cellNumber
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.className, forKey: "name")
        aCoder.encode(self.roomName, forKey: "room")
        aCoder.encode(self.cellNumber, forKey: "number")
    }

    required init?(coder aDecoder: NSCoder) {
        self.className = aDecoder.decodeObject(forKey: "name") as! String
        self.roomName = aDecoder.decodeObject(forKey: "room") as! String
        self.cellNumber = aDecoder.decodeInteger(forKey: "number")
    }
}

希望动下你的小手支持一下,你的支持才是我发帖的动力。

 类似资料: