问题描述
我有一个名为Jar
的结构,我想将它们的数组保存到NSUserDefaults中.这是jar结构代码:
I have a struct named Jar
and I would like to save an array of them to NSUserDefaults. Here is the jar struct code:
struct Jar {
let name: String
let amount: Int
init(name: String, amount: Int){
self.name = name
self.amount = amount
}
}
我相信我将需要将其转换为NSObject才能保存它. (因为您不能将结构直接保存到NSUserDefaults中).我的问题是:如何将结构数组转换为NSObject?和如何将NSObject转换回结构数组.
I belive that I will need to convert this to an NSObject to be able to save it. (Because you can't save a struct directly to NSUserDefaults). My questions are:How do I convert an array of structs to an NSObject? and How to convert an NSObject back at an array of structs.
推荐答案
此解决方案的灵感来自@DuncanC.我编写了与自定义类编码和解码类似的方式.
This solution is inspired by @Duncan C. I wrote it more familiar way as we do in case Custom Class encoding and decoding.
public struct IRDriver {
public var name: String?
public var amount: Int?
public init() {
}
// Decode
public init(dictionary: Dictionary<String, AnyObject>){
name = dictionary["name"] as? String
amount = dictionary["amount"] as? Int
}
// Encode
public func encode() -> Dictionary<String, AnyObject> {
var dictionary : Dictionary = Dictionary<String, AnyObject>()
dictionary["name"] = name
dictionary["amount"] = amount
return dictionary
}
}
这篇关于如何在Swift 2.0中将结构保存到NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!