我有一个enum
,以及一个指向enum
中某个对象的变量。
enum Collection {
case First, Second, Third, Fourth
}
var myCollection = Collection.Second
我想将myCollection
传递给NSUserDefaults
。这就是我所做的:(我希望viewDidLoad
是正确的地方。)
override func viewDidLoad() {
super.viewDidLoad()
// Save the sort by NSUserDefualt
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(self.myCollection, forKey: "myKey")
}
在最后一行,我收到以下错误:
无法使用类型为'(myViewController.Collection,forKey:String)'的参数列表调用'setObject'
我做错了什么,我该如何解决?
更新
这有意义吗?
let defaults = NSUserDefaults.standardUserDefaults()
let defaultRawValue = defaults.integerForKey("myKey")
if defaultRawValue != nil {
defaults.setInteger(myCollection.rawValue, forKey: "myKey")
} else {
defaults.setInteger(1, forKey: "myKey")
}
myCollection = Collection(rawValue: defaultRawValue)!
答案 0 :(得分:1)
NSUserDefaults只能使用PropertyList:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html
尝试
enum Collection:Int{
case First=1, Second, Third, Fourth
}
var myCollection = Collection.Second
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
let defaultRawValue = defaults.integerForKey("myKey")
if defaultRawValue > 0{
myCollection = Collection(rawValue: defaultRawValue)!
}
else
{
defaults.setInteger(1, forKey: "myKey")
myCollection = Collection(rawValue: 1)
}
}
答案 1 :(得分:0)
NSUserDefaults类提供了访问常用类型(如浮点数,双精度数,整数,布尔值和URL)的便捷方法。默认对象必须是属性列表,即(或集合的实例组合)的实例:NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary。
因此,如果要将枚举存储在NSUserDefaults中,可以使用rawValue作为枚举。在这里我使用String,如下所示:
enum Collection: String {
case First = "First"
case Second = "Second"
case Third = "Third"
case Fourth = "Fourth"
}
//create myCollection
var myCollection = Collection(rawValue: "Second")
并存储它:
override func viewDidLoad() {
super.viewDidLoad()
// Save the sort by NSUserDefualt
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(self.myCollection.rawValue, forKey: "myKey")
}