NSCoder的一个自定义类数组

时间:2017-07-05 21:55:15

标签: arrays swift nsuserdefaults nscoder

我使用UserDefaults存储数据,特别是Workout类型的数组。在Workout类中是一个类型为Exercise的数组。当我调用save函数来保存数据时,代码在编码Exercise数组时崩溃。我的设置有什么问题?

enum Type: String {
    case Interval
    case Count
}

class Exercise: NSObject, NSCoding{
    var reps: Int = 1
    var numberOf: Int = 1
    var name: String = "New Exercise"
    var type: Type = .Interval

    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "exerciseName")
        aCoder.encode(reps, forKey: "exerciseReps")
        aCoder.encode(type, forKey: "exerciseType")
        aCoder.encode(numberOf, forKey: "exerciseNumberOf")
    }

    required init(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObject(forKey: "exerciseName") as! String
        reps = aDecoder.decodeObject(forKey: "exerciseReps") as! Int
        numberOf = aDecoder.decodeObject(forKey: "exerciseNumberOf") as! Int
        type = aDecoder.decodeObject(forKey: "exerciseType") as! Type

        super.init()
    }

    override init() {
        super.init()
    }

}

class Workout: NSObject, NSCoding {
    var name: String = "My Workout"
    var lastUsedDate: Date? = nil
    var exerciseList: [Exercise] = []


    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(lastUsedDate, forKey: "lastUsedDate")

        // Code crashes here:
        aCoder.encode(exerciseList, forKey: "exerciseData")

    }

    required init(coder aDecoder: NSCoder) {
        super.init()

        self.name = aDecoder.decodeObject(forKey: "name") as! String
        self.lastUsedDate = aDecoder.decodeObject(forKey: "lastUsedDate") as? Date
        self.exerciseList = aDecoder.decodeObject(forKey: "exerciseData") as! [Exercise]
    }

    override init() {
        super.init()
    }
}

保存并加载功能

func save() {
    let data = NSKeyedArchiver.archivedData(withRootObject: workouts )
    UserDefaults.standard.setValue(data, forKey: "data")

}

func load() {
    if let storedArray = UserDefaults.standard.object(forKey: "data") as? Data {
        workouts = NSKeyedUnarchiver.unarchiveObject(with: storedArray) as! [Workout]
    }
}

0 个答案:

没有答案