Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 590
Pranav Wadhwa Avatar asked Jun 20 '16 14:06

Pranav Wadhwa


People also ask

What is NSCoding in Swift?

The NSCoding protocol declares the two methods that a class must implement so that instances of that class can be encoded and decoded. This capability provides the basis for archiving (where objects and other structures are stored on disk) and distribution (where objects are copied to different address spaces).

What is an NSCoder?

NSCoder declares the interface used by concrete subclasses to transfer objects and other values between memory and some other format. This capability provides the basis for archiving (storing objects and data on disk) and distribution (copying objects and data items between different processes or threads).


1 Answers

The encode method in Swift 3 has been renamed to

func encode(with aCoder: NSCoder) 

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.
like image 56
vadian Avatar answered Jan 28 '23 06:01

vadian