Xcode 如何使用NSCoding将Int编码为可选的
我试图在自定义类中将两个属性声明为optionals—字符串和Int 我在课堂上这样做:Xcode 如何使用NSCoding将Int编码为可选的,xcode,swift,optional,Xcode,Swift,Optional,我试图在自定义类中将两个属性声明为optionals—字符串和Int 我在课堂上这样做: var myString: String? var myInt: Int? 我可以按如下方式解码它们: required init?(coder aDecoder: NSCoder) { myString = aDecoder.decodeObjectForKey("MyString") as? String myInt = aDecoder.decodeIntegerForKey("MyInt"
var myString: String?
var myInt: Int?
我可以按如下方式解码它们:
required init?(coder aDecoder: NSCoder) {
myString = aDecoder.decodeObjectForKey("MyString") as? String
myInt = aDecoder.decodeIntegerForKey("MyInt")
}
aCoder.encodeInteger(myInt!, forKey: "MyInt")
但对它们进行编码会在Int行上出现错误:
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(myInt, forKey: "MyInt")
aCoder.encodeObject(myString, forKey: "MyString")
}
只有当XCode提示我按如下方式展开Int时,错误才会消失:
required init?(coder aDecoder: NSCoder) {
myString = aDecoder.decodeObjectForKey("MyString") as? String
myInt = aDecoder.decodeIntegerForKey("MyInt")
}
aCoder.encodeInteger(myInt!, forKey: "MyInt")
但这显然会导致崩溃。所以我的问题是,我怎样才能让Int像字符串一样被视为可选的呢?我遗漏了什么?如果它可以是可选的,那么您也必须使用
encodeObject
您正在使用Objective-C框架,Objective-C仅允许对象(类/引用类型)使用nil
。在Objective-C中,整数不能是nil
但是,如果您使用encodeObject
,Swift将自动将您的Int
转换为NSNumber
,可以是nil
另一个选项是完全跳过该值:
if let myIntValue = myInt {
aCoder.encodeInteger(myIntValue, forKey: "MyInt")
}
解码时使用
包含值forkey(:)
。感谢您的回答和解释。我现在使用myInt=aDecoder.decodeObjectForKey(“myInt”)作为?encodeObject(myInt,forKey:“myInt”),它工作正常。