in my first project I was creating a class using the following code:
import Foundation
class Rate {
var currency: String!
var sellRate: String!
var buyRate: String!
init (data: NSDictionary) {
self.currency = getStringFromJSON(data, key:"CurrencyName")
self.sellRate = getStringFromJSON(data, key:"SellRate")
self.buyRate = getStringFromJSON(data, key:"BuyRate")
}
func getStringFromJSON(data: NSDictionary, key: String) -> String {
if let info = data[key] as? String {
return info
}
return ""
}
}
I am scratching my head of how to update code to use NSCoding. I need to use NSKeyedArchiver that is why objects should conform to the NSCoding protocol.
I have working example which I found in GitHub, but still I fail to write working code. Example:
class Book: NSObject, NSCoding {
var title: String!
var author: String!
required convenience init(coder decoder: NSCoder) {
self.init()
self.title = decoder.decodeObjectForKey("title") as! String?
self.author = decoder.decodeObjectForKey("author")as! String?
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.title, forKey: "title")
coder.encodeObject(self.author, forKey: "author")
}
}
You already have code for the answer. Your Rate class has three data instances: currency, sellrate, and buyrate. Your sample code used title and author. Add the
: NSObject, NSCoding
after Rate. Copy your sample code into your class. Change all occurrences of title to currency, then duplicate all of these lines but then changing currency to sellrate on these duplicate lines, and change author to buyrate.Try this:
Changes to your original code:
data
label in yourinit
was made optional with a_
.Rate
class inherits fromNSObject
now, it must callsuper.init()
NSCoding
protocolSwiftStub