Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xcode 如何使用NSCoding将Int编码为可选的_Xcode_Swift_Optional - Fatal编程技术网

Xcode 如何使用NSCoding将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"

我试图在自定义类中将两个属性声明为optionals—字符串和Int

我在课堂上这样做:

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”),它工作正常。