76

I created a Swift class that conforms to NSCoding. (Xcode 6 GM, Swift 1.0)

import Foundation

private var nextNonce = 1000

class Command: NSCoding {

    let nonce: Int
    let string: String!

    init(string: String) {
        self.nonce = nextNonce++
        self.string = string
    }

    required init(coder aDecoder: NSCoder) {
        nonce = aDecoder.decodeIntegerForKey("nonce")
        string = aDecoder.decodeObjectForKey("string") as String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeInteger(nonce, forKey: "nonce")
        aCoder.encodeObject(string, forKey: "string")
    }
}

But when I call...

let data = NSKeyedArchiver.archivedDataWithRootObject(cmd);

It crashes gives me this error.

2014-09-12 16:30:00.463 MyApp[30078:60b] *** NSForwarding: warning: object 0x7a04ac70 of class '_TtC8MyApp7Command' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[MyApp.Command replacementObjectForKeyedArchiver:]

What should I do?

Hlung
  • 13,850
  • 6
  • 71
  • 90
  • 2
    Here is the best answer http://stackoverflow.com/a/24416671/1118772 – Noundla Sandeep Nov 18 '14 at 07:06
  • @noundla No, the answer in your link doesn't work with my problem. I tried both the solutions. 1) Adding `@objc` to my Command class and NSCoding methods still gives me the same error. 2) Adding `NSObject` is just the same as my answer. You better try it first next time. – Hlung Nov 18 '14 at 07:50
  • I had the same issue yesterday and that solutions worked for me. I used both 1 & 2 solutions to solve the issue. – Noundla Sandeep Nov 19 '14 at 13:21
  • @noundla Weird. May be it's just because our problems are different. Yours is about `performSelector:`, but mine is about NSCoding protocol. – Hlung Nov 20 '14 at 04:30

1 Answers1

237

Although Swift class works without inheritance, but in order to use NSCoding you must inherit from NSObject.

class Command: NSObject, NSCoding {
    ...
}

Too bad the compiler error is not very informative :(

Hlung
  • 13,850
  • 6
  • 71
  • 90
  • 1
    I have this issue when returning a custom Swift object inside a dictionary to a callback block. I would like to know how I was supposed to know that values in those dictionaries had to conform to `NSCoding`. – Rivera Apr 01 '15 at 14:57
  • @Rivera `NSCoding` protocol allows object to be converted to `NSData` object so you can do things like store it in NSUserDefaults, etc. I don't actually know if what you are doing needs this. That's all I can say. – Hlung Apr 02 '15 at 05:03
  • I was working with WatchKit. The reason was that dictionaries passed as parameters have to be Property List-compatibles. It is not documented but shows up in the console logs. – Rivera Apr 02 '15 at 11:40
  • And you have to have NSObject as the first in the inheritance clause. – Pei Apr 06 '18 at 14:35