1

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?

Community
  • 1
  • 1
Zitong
  • 13
  • 4

1 Answers1

1

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.

Renzo
  • 26,848
  • 5
  • 49
  • 61
  • Thank you! And I want to know `Character(abc)` and `String(abc)` wether cost a lot system resources. Beacuse I will have thousands of objects to deal with. – Zitong Aug 27 '15 at 06:52
  • I don't think these operations will cost too much, since they can be efficiently executed in O(1) time. – Renzo Aug 27 '15 at 06:54
  • And do you know other method to solve it without convert between character and string? – Zitong Aug 27 '15 at 06:55
  • Maybe you could change the representation of characters and use an Int instead, using `encodeInt:forKey` and `decodeIntForKey`, and then converting the integer to a character only when you need to print it? – Renzo Aug 27 '15 at 06:59
  • Thanks. I need a Character to be a key in my class, and all of characters are Chinese utf-8 characters. :-( – Zitong Aug 27 '15 at 07:04