davidmark
davidmark

Reputation: 23

Can someone explain how to use NSKeyedArchiver and NSKeyedUnarchiver in Swift?

I have troubles understanding NSKeyedArchiver and NSKeyedUnarchiver in Swift.

This is some example code I have been given to get a picture of its use:

class Workout : NSObject, Coding {
    var name: String!
    var entries: Int = 0

    required convenience init(coder aDecoder: NSCoder) {
        self.init()
        name = aDecoder.decodeObject(forKey: "name") as! String
        entries = aDecoder.decodeInteger(forKey: "entries")
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.entries, forKey: "entries")
    }
}

let libDir = FileManager.default.urls(for: .libraryDirectory,
                                   in: .userDomainMask)[0]
print(libDir)

let workout = Workout()
workout.entries = 14
workout.name = "Pull-ups"

let path = libDir.appendingPathComponent("workouts")

// Serialisere til disk
if let data = try? NSKeyedArchiver.archivedData(withRootObject: workout, requiringSecureCoding: true) {
    try? data.write(to: path)
}

// Deserialisere fra disk
if let archivedData = try? Data(contentsOf: path),
        let savedWorkout = (try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(archivedData)) as? Workout {
    print("\(savedWorkout.name), entries: \(savedWorkout.entries)")
}

I somehow get how NSKeyedArchiver works, but the Workout class in NSKeyedUnarchiver is something i find difficult to understand. What is going on in the class? And when i try to paste the class in a new swift file, I get this error: "Cannot find type 'Coding' in scope".

Upvotes: 0

Views: 777

Answers (0)

Related Questions