如何使用NSCoding将Int编码为可选 [英] How to encode Int as an optional using NSCoding
问题描述
我试图在自定义类中将两个属性声明为可选属性-String和Int.
I am trying to declare two properties as optionals in a custom class - a String and an Int.
我正在MyClass中这样做:
I'm doing this in 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")
}
但是对它们进行编码会在Int行上产生错误:
But encoding them gives an error on the Int line:
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(myInt, forKey: "MyInt")
aCoder.encodeObject(myString, forKey: "MyString")
}
仅当XCode提示我打开Int时,错误才会消失:
The error only disappears when XCode prompts me to unwrap the Int as follows:
aCoder.encodeInteger(myInt!, forKey: "MyInt")
但这显然会导致崩溃.所以我的问题是,如何使Int像String一样被视为可选内容?我想念什么?
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?
推荐答案
如果可以选择,也必须使用encodeObject
.
If it can be optional, you will have to use encodeObject
for it, too.
您正在使用Objective-C框架,而Objective-C仅允许nil
用于对象(类/引用类型).在Objective-C中,整数不能为nil
.
You are using an Objective-C framework and Objective-C allows nil
only for objects (class/reference types). An integer cannot be nil
in Objective-C.
但是,如果您使用encodeObject
,Swift将自动将您的Int
转换为NSNumber
,可以是nil
.
However, if you use encodeObject
, Swift will automatically convert your Int
to NSNumber
, which can be nil
.
另一种选择是完全跳过该值:
Another option is to skip the value entirely:
if let myIntValue = myInt {
aCoder.encodeInteger(myIntValue, forKey: "MyInt")
}
,并在解码时使用containsValueForKey(_:)
.
这篇关于如何使用NSCoding将Int编码为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!