gpt4 book ai didi

ios - 将对象添加到枚举给我错误

转载 作者:行者123 更新时间:2023-11-29 01:41:39 28 4
gpt4 key购买 nike

我有一个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")
}

在最后一行,我收到以下错误:

Cannot invoke 'setObject' with an argument list of type '(myViewController.Collection, forKey: String)'

我做错了什么,我该如何解决?

更新

这有意义吗?

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)!

最佳答案

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)
}
}

关于ios - 将对象添加到枚举给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322215/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com