本文介绍了无法在 Swift 中使用 NSCoder 解码 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 3.0 中使用 Xcode8 Beta.我试图基于 NSObject 编码一个简单的对象,但我无法解码 Int 或 NSInteger 类型.(编码过程没问题)

I am using Xcode8 Beta with Swift 3.0. I tried to encode a simple object base on NSObject, but I cannot decode Int or NSInteger type. (The encoding process is OK)

代码

class Model : NSObject, NSCoding {
    var seq: NSNumber?
    var seq2: Int? // problem with seq2, NSInteger is not ok, either
    var id: String?
    var value: String?

    override init() {
        super.init()
    }

    required init?(coder aDecoder: NSCoder){
        self.seq = aDecoder.decodeObject(forKey: "seq") as? NSNumber
        self.seq2 = aDecoder.decodeInteger(forKey: "seq2")
        self.id = aDecoder.decodeObject(forKey: "id") as? String
        self.value = aDecoder.decodeObject(forKey: "value") as? String
    }

    func encode(with aCoder: NSCoder){
        aCoder.encode(seq, forKey: "seq")
        aCoder.encode(seq2, forKey: "seq2")
        aCoder.encode(id, forKey: "id")
        aCoder.encode(value, forKey: "value")
    }
}

推荐答案

问题在于 seq2 不是 Int,而是 Int? 可选.它不能表示为 Objective-C 整数.

The problem is that seq2 is not an Int, but rather a Int? optional. It cannot be represented as an Objective-C integer.

你可以使用decodeObject:

required init?(coder aDecoder: NSCoder){
    self.seq = aDecoder.decodeObject(forKey: "seq") as? NSNumber
    self.seq2 = aDecoder.decodeObject(forKey: "seq2") as? Int
    self.id = aDecoder.decodeObject(forKey: "id") as? String
    self.value = aDecoder.decodeObject(forKey: "value") as? String

    super.init()
}

或更改它使其不是可选的:

or change it so it is not optional:

class Model : NSObject, NSCoding {
    var seq: NSNumber?
    var seq2: Int
    var id: String?
    var value: String?

    init(seq: NSNumber, seq2: Int, id: String, value: String) {
        self.seq = seq
        self.seq2 = seq2
        self.id = id
        self.value = value

        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        self.seq = aDecoder.decodeObject(forKey: "seq") as? NSNumber
        self.seq2 = aDecoder.decodeInteger(forKey: "seq2")
        self.id = aDecoder.decodeObject(forKey: "id") as? String
        self.value = aDecoder.decodeObject(forKey: "value") as? String

        super.init()
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(seq, forKey: "seq")
        aCoder.encode(seq2, forKey: "seq2")
        aCoder.encode(id, forKey: "id")
        aCoder.encode(value, forKey: "value")
    }

    override var description: String { return "<Model; seq=\(seq); seq2=\(seq2); id=\(id); value=\(value)>" }
}

这篇关于无法在 Swift 中使用 NSCoder 解码 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:22