Swift: Does not conform to protocol NSCoding

前端 未结 3 1919
一个人的身影
一个人的身影 2020-12-17 17:49

I am trying to use the NSCoding protocol on a class I have written in swift, but cannot seem to figure out why the compiler complains that it \"does not conform to protocol

相关标签:
3条回答
  • 2020-12-17 18:02

    As you can see in the detailed compiler messages in the Report navigator, your methods are not declared correctly:

    error: type 'ServerInfo' does not conform to protocol 'NSCoding'
    class ServerInfo: NSObject, NSCoding {
    ^
    Foundation.NSCoding:2:32: note: protocol requires function 'encodeWithCoder' with type '(NSCoder) -> Void'
      @objc(encodeWithCoder:) func encodeWithCoder(aCoder: NSCoder)
                                   ^
    note: candidate has non-matching type '(NSCoder!) -> ()'
        func encodeWithCoder(_aCoder: NSCoder!) {
             ^
    Foundation.NSCoding:3:25: note: protocol requires initializer 'init(coder:)' with type '(coder: NSCoder)'
      @objc(initWithCoder:) init(coder aDecoder: NSCoder)
                            ^
    note: candidate has non-matching type '(coder: NSCoder!)'
        init(coder aDecoder: NSCoder!) {
    

    (This may have changed between the beta releases.) In addition, the initWithCoder method has to be marked as required:

    required init(coder aDecoder: NSCoder) {   }
    
    func encodeWithCoder(_aCoder: NSCoder) {   }
    

    In Swift 3 the required methods are

    required init(coder aDecoder: NSCoder) {   }
    
    func encode(with aCoder: NSCoder) {   }
    
    0 讨论(0)
  • 2020-12-17 18:11

    The parameters are not implicitly unwrapped (remove the !), and the initializer requires the required modifier:

    required init(coder aDecoder: NSCoder) {
    ...
    func encodeWithCoder(_aCoder: NSCoder) {
    

    For Swift 3

    A minor but important change has been commited . The init method is same but the encodeWithCoder method has been modified.

       required init(coder aDecoder: NSCoder) {
        ...
       }
    
       func encode(with _aCoder: NSCoder) { 
       ...
       }
    
    0 讨论(0)
  • 2020-12-17 18:16

    For Swift 3 (on Xcode 8.2 beta (8C23))

    It appears to have changed again. This is the only variation that I could get to work...

    func encodeWithCoder(_ _aCoder: NSCoder) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题