When archive object in the func encode(with aCoder: NSCoder) method crashed with swift enum in real revice

后端 未结 1 1257
北海茫月
北海茫月 2021-01-19 14:43

In my singleton class, I have a swift enum here:

import UIKit

enum UserType {
    case terant  // 
    case normalUser  // 
    cas         


        
相关标签:
1条回答
  • 2021-01-19 15:23

    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.

    0 讨论(0)
提交回复
热议问题