In my singleton
class, I have a swift
enum here:
import UIKit
enum UserType {
case terant //
case normalUser //
cas
Try this for your Question
func encode(with aCoder: NSCoder) {
aCoder.encode(type.rawValue, forKey: "type")
}
For More Information
Let Discuss this problem in details
For example, this is my Enum:
enum PieceType : Int {
case empty
case notEmpty
}
And this is my Object which is child of NSObject
class Piece: NSObject, NSCoding {
var islogin: Bool
var type: PieceType
var username: String!
var password: String!
override init() {
islogin = false
type = PieceType.empty
username = ""
password = ""
}
required init(coder aDecoder: NSCoder) {
islogin = aDecoder.decodeBool(forKey: "islogin")
type = PieceType(rawValue: aDecoder.decodeObject(forKey: "type") as! Int)!
username = aDecoder.decodeObject(forKey: "username") as! String
password = aDecoder.decodeObject(forKey: "password") as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(islogin, forKey: "islogin")
aCoder.encode(type.rawValue, forKey: "type")
aCoder.encode(username, forKey: "username")
aCoder.encode(password, forKey: "password")
}
}
When you call NSKeyedArchiver.archiveRootObject(::)
it will call func encode(with aCoder: NSCoder)
method and convert your NSObject
to Data And when you try to Unarchive your object it will call init(coder aDecoder: NSCoder)
method and convert Data to NSObject
by using Key.
But in Enum
case you can not encode enum
directly B'Coz it is User Define data type but rawValue
is must be inbuilt data type like Int, String,Float.....So on.
that's why when you try to encode enum
you need to use rawValue
I Hope you will get point.