How to encode Int as an optional using NSCoding

谁说胖子不能爱 提交于 2019-12-18 14:56:36

问题


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

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")
}

But encoding them gives an error on the Int line:

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:

  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?


回答1:


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

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.

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")
}

and use containsValueForKey(_:) when decoding.



来源:https://stackoverflow.com/questions/36154590/how-to-encode-int-as-an-optional-using-nscoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!