Like
How do I encode enum using NSCoder in swift?
Code :
import Foundation
class Car: NSObject, NSCoding {
var bmw: Character
required init(coder decoder: NSCoder) {
bmw = (decoder.decodeObjectForKey("bmw") as? Character)!
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(bmw, forKey: "bmw")
}
}
Xcode throw an error :
Cannot invoke 'encodeObject' with an argument list of type '(Characher, forKey: String)'
What should I do with Character in swift?
The reason of the error is that, while String
is subtype of AnyObject
, Character
is not (since a character is not an object). A way to solve your problem could be the following:
class Car: NSObject {
var bmw: Character
required init(coder decoder: NSCoder) {
bmw = Character(decoder.decodeObjectForKey("bmw") as! String)
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(String(bmw), forKey: "bmw")
}
}
Here you convert the character to a string before encoding it, and convert back to character after decoding.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.