[英]How to save struct to NSUserDefaults in Swift 2.0
I have a struct named Jar
and I would like to save an array of them to NSUserDefaults. 我有一个名为
Jar
的结构,我想将它们的数组保存到NSUserDefaults。 Here is the jar struct code: 这是jar结构代码:
struct Jar {
let name: String
let amount: Int
init(name: String, amount: Int){
self.name = name
self.amount = amount
}
}
I belive that I will need to convert this to an NSObject to be able to save it. 我相信我将需要将其转换为NSObject才能保存它。 (Because you can't save a struct directly to NSUserDefaults).
(因为不能将结构直接保存到NSUserDefaults中)。 My questions are: How do I convert an array of structs to an NSObject?
我的问题是: 如何将结构数组转换为NSObject? and How to convert an NSObject back at an array of structs.
以及如何将NSObject转换回结构数组。
This solution is inspired by @Duncan C. I wrote it more familiar way as we do in case Custom Class encoding and decoding. 该解决方案的灵感来自@DuncanC。我编写了一种更熟悉的方法,就像在定制类编码和解码的情况下一样。
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
}
}
For saving to user defaults you have a couple of options: Have the object conform to NSCoding, or implement methods that convert it to/from an NSDictionary, and save that. 要保存为用户默认值,您有两个选择:使对象符合NSCoding,或实现将其转换为NSDictionary或从NSDictionary转换为该对象的方法,并保存该对象。
Something like this: 像这样:
func dictionaryFromJar() -> NSDictionary
{
let dictionary: [AnyObject: AnyObject] = ["name": name, "amount": amount]
return dictionary
}
I think the automatic bridging between Swift dictionaries and NSDictionary would work here, but I'm not positive. 我认为Swift字典和NSDictionary之间的自动桥接可以在这里工作,但我并不乐观。 My swift is getting a little rusty.
我的速度有点生锈了。 :(
:(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.