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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
I don't think these operations will cost too much, since they can be efficiently executed in O(1) time.
And do you know other method to solve it without convert between character and string?
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?
Thanks. I need a Character to be a key in my class, and all of characters are Chinese utf-8 characters. :-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.