Got Unrecognized selector -replacementObjectForKeyedArchiver: crash when implementing NSCoding in Swift
Asked Answered
R

1

77

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?

Roulers answered 12/9, 2014 at 9:56 Comment(4)
Here is the best answer https://mcmap.net/q/23621/-object-x-of-class-y-does-not-implement-methodsignatureforselector-in-swiftGuillermo
@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.Roulers
I had the same issue yesterday and that solutions worked for me. I used both 1 & 2 solutions to solve the issue.Guillermo
@noundla Weird. May be it's just because our problems are different. Yours is about performSelector:, but mine is about NSCoding protocol.Roulers
R
239

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 :(

Roulers answered 12/9, 2014 at 9:57 Comment(4)
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.Kessel
@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.Roulers
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.Kessel
And you have to have NSObject as the first in the inheritance clause.Exchangeable

© 2022 - 2024 — McMap. All rights reserved.