ios - 可选值的 NSCoder decodeDouble

标签 ios swift nscoding nscoder

NSCoder 上的 decodeDouble 返回一个非可选值,但我想确定一个值在编码之前是否为 nil。

这是我的场景:

var optionalDouble: Double? = nil

func encode(with aCoder: NSCoder) {
    if let optionalDouble {
        aCoder.encode(optionalDouble, forKey: "myOptionalDouble")
    }
}

convenience required init?(coder aDecoder: NSCoder) {
    optionalDouble = aDecoder.decodeDouble(forKey: "myOptionalDouble") 
    // here optionalDouble is never nil anymore
}

因此,解码 double 返回 0,以防从未设置值,所以我似乎无法确定值实际上是 0 还是 nil 编码前

有没有办法让我在编码之前检查一个 double 是否为 nil?

最佳答案

解决方案是在编码时使用 NSNumber 而不是 Double,然后使用 decodeObject 取回(如果存在)double 值。例如

class A: NSCoding {
    var optionalDouble: Double? = nil

    @objc func encodeWithCoder(aCoder: NSCoder) {
        if let optionalDouble = optionalDouble {
            aCoder.encodeObject(NSNumber(double: optionalDouble), forKey: "myOptionalDouble")
        }
    }

    @objc required init?(coder aDecoder: NSCoder) {
        if let decodedDoubleNumber = aDecoder.decodeObjectForKey("myOptionalDouble") as? NSNumber {
            self.optionalDouble = decodedDoubleNumber.doubleValue
        } else {
            self.optionalDouble = nil
        }
    }
}

根据@Hamish 的建议,这里是 Swift 3 的版本。请注意,我们需要将类继承到 NSObject 以使 NSEncoding 工作(Got Unrecognized selector -replacementObjectForKeyedArchiver: crash when implementing NSCoding in Swift)

class A: NSObject, NSCoding {
    var optionalDouble: Double? = nil

    func encode(with aCoder: NSCoder) {
        if let optionalDouble = optionalDouble {
            aCoder.encode(optionalDouble, forKey: "myOptionalDouble")
        }
    }

    override init() {
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        optionalDouble = aDecoder.decodeObject(forKey: "myOptionalDouble") as? Double
    }
}

关于ios - 可选值的 NSCoder decodeDouble,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40785028/

相关文章:

ios - Swift 2 无法使用类型的参数列表调用 'FSEventStreamCreate'

ios - 在 iOS 上通过 twitter 登录并在我的服务器上进行身份验证

objective-c - 如何使用 NSCoding 序列化 C 数组?

iphone - 无法弄清楚为什么我的应用程序在使用 NSKeyedArchivers/NSKeyedUnarchivers 时崩溃

iOS In App Purchase 功能显示 : "An App ID with Identifier ' com. 示例。App' 不可用”

objective-c - iOS 开发 - 如何从自定义 View Controller 类接收按钮事件?

ios - TableView崩溃了,为什么它还是这样竖着呢?

ios - swift NSKeyedArchiver : Do custom members of an NSCoding-conformant class need to conform to NSCoding as well?

ios - 用于 Flutter iOS Swift 设置的谷歌地图

objective-c - 如何在 xcode 4.5 中创建倒数计时器