How to use state restoration properly here ?

Hi, I'm trying to save the state of some switches and restore it when the app launches again but when I wrote this :


override func encodeRestorableState(with coder: NSCoder) {

super.encodeRestorableState(with: coder)

coder.encode(Int32(self.runSwitch1.state.rawValue), forKey: CodingKey.Protocol)

}


I got this error : Cannot convert value of type 'CodingKey.Protocol.Type' to expected argument type 'String'


What should I do ?

Replies

You seem to be mixing up Swift’s

Codable
(which is where
CodingKey
comes from) with the traditional Cocoa
NSCoder
. These are very different beasts.
encode(_:forKey:)
is an
NSCoder
method, and it takes a string for the
forKey
parameter. Traditionally you’d use something that describes the meaning of the encoded item, like
runSwitch1State
.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I'm pretty new to swift and I don't understand ,how should I rewrite my code ?

The second parameter to

encode(_:forKey:)
has to be a string.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"