xcode 如何使用 NSCoding 将 Int 编码为可选

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36154590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:38:51  来源:igfitidea点击:

How to encode Int as an optional using NSCoding

xcodeswiftoptional

提问by Eatton

I am trying to declare two properties as optionals in a custom class - a String and an Int.

我试图在自定义类中将两个属性声明为可选属性 - String 和 Int。

I'm doing this in MyClass:

我在 MyClass 中这样做:

var myString: String?
var myInt: Int?

I can decode them ok as follows:

我可以按如下方式解码它们:

required init?(coder aDecoder: NSCoder) {
  myString = aDecoder.decodeObjectForKey("MyString") as? String
  myInt = aDecoder.decodeIntegerForKey("MyInt")
}

But encoding them gives an error on the Int line:

但是对它们进行编码会在 Int 行上出现错误:

func encodeWithCoder(aCoder: NSCoder) {
  aCoder.encodeInteger(myInt, forKey: "MyInt")
  aCoder.encodeObject(myString, forKey: "MyString")
}

The error only disappears when XCode prompts me to unwrap the Int as follows:

只有当 XCode 提示我解开 Int 时,错误才会消失,如下所示:

  aCoder.encodeInteger(myInt!, forKey: "MyInt")

But that obviously results in a crash. So my question is, how can I get the Int to be treated as an optional like the String is? What am I missing?

但这显然会导致崩溃。所以我的问题是,如何让 Int 像 String 一样被视为可选项?我错过了什么?

回答by Sulthan

If it can be optional, you will have to use encodeObjectfor it, too.

如果它可以是可选的,那么您也必须使用encodeObject它。

You are using an Objective-C framework and Objective-C allows nilonly for objects (class/reference types). An integer cannot be nilin Objective-C.

您使用的是 Objective-C 框架,而 Objective-Cnil仅允许对象(类/引用类型)。整数不能nil在 Objective-C 中。

However, if you use encodeObject, Swift will automatically convert your Intto NSNumber, which can be nil.

但是,如果您使用encodeObject,Swift 会自动将您转换IntNSNumber,也可以是nil.

Another option is to skip the value entirely:

另一种选择是完全跳过该值:

if let myIntValue = myInt {
    aCoder.encodeInteger(myIntValue, forKey: "MyInt")
}

and use containsValueForKey(_:)when decoding.

containsValueForKey(_:)在解码时使用。