penatheboss penatheboss - 5 months ago 42
iOS Question

Does not conform to protocol 'NSCoding' - Swift 3

I have seen several questions similar to mine; however, those are pertaining to swift 2/1 and I am currently using swift 3. I believe Apple has changed it slightly.

class Person: NSObject, NSCoding {

var signature: UIImage

init(signature: UIImage) {
self.signature = signature
}

required convenience init(coder aDecoder: NSCoder) {
let signature = aDecoder.decodeObject(forKey: "signature") as! UIImage
self.init(signature: signature)
}

func encodeWithCoder(aCoder: NSCoder) {
aCoder.encode(signature, forKey: "signature")
}

}


You will notice how Swift 3 now forces me to use
required convenience init(
instead of
required init(
. Perhaps that has something to do with it.

How can I resolve this issue? Thanks!

Answer

The syntax of the encode method in Swift 3 has been renamed to

func encode(with aCoder: NSCoder) {
  aCoder.encode(signature, forKey: "signature")
}

When you get the do not conform error you can easily find out which required methods are missing

  • Press ⌘B to build the code.
  • Press ⌘4 to show the issue navigator.
  • Click on the disclosure triangle in front of the issue line.