我使用以下代码使用Swift将值设置为NSUserDefaults。这是我的代码:
let key = "ticker"
let currencyTickerData = [key:"USD"]
NSUserDefaults.standardUserDefaults().setObject(currencyTickerData, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
let tickerVal : [NSString]? = (NSUserDefaults.standardUserDefaults().objectForKey(key)) as? [NSString]
print(tickerVal)
出于某种原因,tickerVal为零。为什么是这样?据我所知,它应该返回“USD。”
答案 0 :(得分:2)
NSUserDefaults使用NSDictionary而不是Swift的字典类型。您可以显式键入tickerVal作为NSDictionary,如下所示:
let key = "ticker"
let currencyTickerData: NSDictionary = [key:"USD"]
NSUserDefaults.standardUserDefaults().setObject(currencyTickerData, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
let tickerVal = (NSUserDefaults.standardUserDefaults().objectForKey(key)) as NSDictionary
print("\(tickerVal)")
答案 1 :(得分:0)
与您保存日期的代码相同:
var myValue:NSString = "USD"
NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"ticker")
NSUserDefaults.standardUserDefaults().synchronize()
var myOutput: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("ticker")
println(myOutput)