0

我使用了以下参考How to use NSUserDefaults to store a array of custom classes in Swift? 在 Swift 中创建一个 UserHours 类并从 UserDefaults 保存/加载数据。但是,当我这样做时,不会保存/加载附加到类的新对象。你能帮我理解我在这里做错了什么吗?我没有在屏幕上看到任何可以帮助我调试的错误日志。

class Database {

    var users = [String: User]()
    var vacationRequest = [VacationRequest]()
    var userHours = [UserHours]()
    let userID = DatabaseInstance.userID
    let userDefaults = UserDefaults.standard

    func addUserHours(hours: UserHours) {
        self.userHours.append(hours)
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.userHours)
        userDefaults.set(encodedData, forKey: DatabaseInstance.userhour)
        userDefaults.synchronize()
    }

    func getUserHours() -> [UserHours] {
        if let data = userDefaults.data(forKey: DatabaseInstance.userhour),
            let userHoursList = NSKeyedUnarchiver.unarchiveObject(with: data) as? [UserHours] {
            self.userHours = userHoursList;
            return userHoursList;
        } else {
            print("There is an issue")
        }
        return self.userHours
    }
}



class UserHours: NSObject, NSCoding{
    var userId: String = ""
    var date: Date = Date()
    var startTime: Date = Date()
    var mealStart: Date = Date()
    var mealEnd: Date = Date()
    var endTime: Date = Date()

    init(userId: String, date: Date, startTime: Date, mealStart: Date, mealEnd : Date, endTime: Date) {
        self.userId = userId
        self.date = date
        self.startTime = startTime
        self.mealStart = mealStart
        self.mealEnd = mealEnd
        self.endTime = endTime
    }

    required convenience init(coder decoder: NSCoder) {
        let userId = decoder.decodeObject(forKey: "userId") as! String
        let date = decoder.decodeObject(forKey: "date") as! Date
        let startTime = decoder.decodeObject(forKey: "startTime") as! Date
        let mealStart = decoder.decodeObject(forKey: "mealStart") as! Date
        let mealEnd = decoder.decodeObject(forKey: "mealEnd") as! Date
        let endTime = decoder.decodeObject(forKey: "endTime") as! Date
        self.init(userId: userId, date: date, startTime: startTime, mealStart: mealStart, mealEnd : mealEnd, endTime: endTime)
    }

    func encode(with coder: NSCoder) {
        coder.encode(userId, forKey: "userId")
        coder.encode(date, forKey: "date")
        coder.encode(startTime, forKey: "startTime")
        coder.encode(mealStart, forKey: "mealStart")
        coder.encode(mealEnd, forKey: "mealEnd")
        coder.encode(endTime, forKey: "endTime")
    }
}
4

0 回答 0