iOS/Swift 1.2 NSDictionray/Dictionary on NSStandardUserDefaults

随声附和 提交于 2019-12-11 04:04:49

问题


In the 'old' Swift, I used to register my defaults loaded from a .plist file like this...

let prefs = NSBundle.mainBundle().pathForResource("UserDefaults", ofType: "plist");
let dict = NSDictionary(contentsOfFile: prefs!);
let defaults:NSDictionary! = dict?.valueForKey("defaults") as! NSDictionary;

NSUserDefaults.standardUserDefaults().registerDefaults(defaults);
NSUserDefaults.standardUserDefaults().synchronize();

Under Swift 1.2, I get the error...

Cannot invoke 'registerDefaults' with an argument list of type '(NSDictionary!)'

So, something has changed and Swift no-longer accepts an NSDictionary as a parameter to registerDefaults.

So, how can I convert my NSDictionary to a Dictionary object, given that they're no-longer interchangeable?


回答1:


You need to provide a type cast from NSDictionary to a [NSObject:AnyObject] -

use

let prefs = NSBundle.mainBundle().pathForResource("UserDefaults", ofType: "plist");
let dict = NSDictionary(contentsOfFile: prefs!);
let defaults:NSDictionary! = dict?.valueForKey("defaults") as! NSDictionary
NSUserDefaults.standardUserDefaults().registerDefaults(defaults as [NSObject : AnyObject]);
NSUserDefaults.standardUserDefaults().synchronize();



回答2:


The user defaults can store NSDictionary objects. These are mapped to Swift as [NSObject : AnyObject]:

Try this:

NSUserDefaults.standardUserDefaults().setObject(defaults, forKey: "defaults")
var isOk = NSUserDefaults.standardUserDefaults().synchronize();


来源:https://stackoverflow.com/questions/29646193/ios-swift-1-2-nsdictionray-dictionary-on-nsstandarduserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!