我使用以下代码将 Set 存储到 NSUserDefaults 中。当我关闭应用程序并再次启动它时,它会中断。NSUserDefaults 语句有一些奇怪的地方,因为如果我省略这段代码,它就可以正常工作。可能是什么原因?
var setOfStrings: Set<String>?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let onlyAtFirstLaunch = NSUserDefaults.standardUserDefaults().objectForKey("arrayFromSet") as? Array<String>
if onlyAtFirstLaunch == nil{
setOfStrings = Set<String>()
}else{
let arrayFromSet = NSUserDefaults.standardUserDefaults().objectForKey("arrayFromSet") as! Array<String>
setOfStrings! = Set(arrayFromSet)
}
}
func applicationDidEnterBackground(application: UIApplication) {
let arrayFromSet = Array(setOfStrings!)
NSUserDefaults.standardUserDefaults().setObject(NSArray(array: arrayFromSet), forKey: "arrayFromSet")
NSUserDefaults.standardUserDefaults().synchronize()
}