1

Let's say I have an object Person. (I know that Person has syntax errors. Please ignore those.)

class Person: NSObject, NSCoding {

    var name : String
    var salary: NSNumber


    // MARK: NSCoding

    required convenience init(coder decoder: NSCoder) {
        self.init()
        self.name = decoder.decodeObjectForKey("name") as String
        self.salary = decoder.decodeObjectForKey("salary") as NSNumber        
    }

    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(self.name, forKey: "name")
        coder.encodeObject(self.salary, forKey: "salary")
    }

}

My question is: Is it possible to have two separate encodeWithCoder methods..one that includes salary in the archived object, and one that does not. Something like:

func encodeWithCoderPrivate(coder: NSCoder) {
    coder.encodeObject(self.name, forKey: "name")
    coder.encodeObject(self.salary, forKey: "salary")
}

func encodeWithCoderPublic(coder: NSCoder) {
    coder.encodeObject(self.name, forKey: "name")
}

What's the best way to go about implementing multiple archive methods in an NSObject, as a way of limiting the fields written to the archive?

Four
  • 406
  • 4
  • 13

1 Answers1

0

Rather than trying to have 2 versions of it you should figure out what it is that determines which encoding you want to use, and make that a separate flag/field and encode that too.

func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(self.name, forKey: "name")
    if self.someFlag == true {
      coder.encodeObject(self.salary, forKey: "salary")
    }
    // encode flag as well
}

Then you can do the same thing in initWithCoder by parsing the flag first and decoding the rest of the fields based on its value.

Dima
  • 23,484
  • 6
  • 56
  • 83
  • This makes sense. Allows me to create a private copy of the data, then encode that copy. Just implemented and works perfectly. Thanks! – Four May 13 '15 at 00:05