本文介绍了使用NSCoding创建一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的第一个项目中,我使用以下代码创建一个类:
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 ""
}
}
我正在摸索如何使用NSCoding更新代码。我需要使用NSKeyedArchiver,这就是为什么对象应符合NSCoding协议的原因。
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.
我有在GitHub中找到的工作示例,但仍然无法编写工作代码。示例:
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")
}
}
推荐答案
尝试一下:
class Rate : NSObject, NSCoding {
var currency: String!
var sellRate: String!
var buyRate: String!
init (_ data: NSDictionary) {
super.init()
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 ""
}
// NSCoding protocol implementation
@objc func encodeWithCoder(coder : NSCoder) {
coder.encodeObject(self.currency, forKey:"currency")
coder.encodeObject(self.sellRate, forKey:"sellRate")
coder.encodeObject(self.buyRate, forKey:"buyRate")
}
@objc required init(coder aDecoder: NSCoder) {
self.currency = aDecoder.decodeObjectForKey("currency") as! String
self.sellRate = aDecoder.decodeObjectForKey("sellRate") as! String
self.buyRate = aDecoder.decodeObjectForKey("buyRate") as! String
}
}
// Usage
let dict = [
"CurrencyName": "USD",
"SellRate": "1.12",
"BuyRate": "1.1"
]
let r1 = Rate(dict)
// Archive it
let data = NSKeyedArchiver.archivedDataWithRootObject(r1)
// Get it back
let r2 = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! Rate
print(r2.currency)
print(r2.sellRate)
print(r2.buyRate)
更改为原始代码:
-
数据$ c
init
中的$ c>标签通过_
设置为可选。 - 由于您的
费率
类现在是从NSObject
继承的,因此必须调用super.init()
- 为
NSCoding
协议添加了实现
- The
data
label in yourinit
was made optional with a_
. - Because your
Rate
class inherits fromNSObject
now, it must callsuper.init()
- Added implementation for
NSCoding
protocol
这篇关于使用NSCoding创建一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!