2014-10-17 80 views
1

我正在使用下面的代碼使用Swift將值設置爲NSUserDefaults。以下是我的代碼:objectForKey在Swift中返回nil爲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爲零。爲什麼是這樣?據我所知,它應該返回「美元」。

+0

與解決類似的問題只是張貼在這裏:http://stackoverflow.com/questions/26424240/save-data-of-a-label-in -swift/26425574#26425574 – 2014-10-17 22:51:12

回答

2

使用NSUserDefaults的NSDictionary的,而不是斯威夫特的字典類型。您可以鍵入明確作爲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)") 
+0

This print「{\ n ticker = USD; \ n}」 – 2014-10-17 23:06:29

+0

您想要打印什麼?如果您只希望tickerVal爲「USD」,請使用'let tickerVal:NSString =((NSUserDefaults.standardUserDefaults()。objectForKey(key))as NSDictionary)[key] as NSString' instead – connor 2014-10-17 23:09:01

+0

完美,謝謝! – 2014-10-17 23:10:19

0

這是相同的代碼,將節省你時間:

var myValue:NSString = "USD" 

NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"ticker") 
NSUserDefaults.standardUserDefaults().synchronize() 

var myOutput: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("ticker") 
println(myOutput) 
+0

This print「Optional(USD)」 – 2014-10-17 23:08:13