我有一个级别设置的plist
defaultPrefs.plist
Root Dictionary
Level1 Dictionary
time Number 0
pushes Number 0
moves Number 0
unlocked Boolean YES
Level2 Dictionary
time Number 0
pushes Number 0
moves Number 0
unlocked Boolean NO
等
我正在AppDelegate中注册它们
let plist: String? = "defaultPrefs"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let path = NSBundle.mainBundle().pathForResource(plist, ofType: "plist")!
let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]
NSUserDefaults.standardUserDefaults().registerDefaults(dict)
}
我想更新这些
func writeToPlist() {
let defaults = NSUserDefaults.standardUserDefaults()
let level1Dict:AnyObject = defaults.objectForKey("Level1")!
//let level1Dict:AnyObject = defaults.dictionaryForKey("Level1")!
level1Dict.setValue(1, forKey: "moves")
//level1Dict.setInteger(1, forKey: "moves")
}
错误:
发送到不可变对象的变异方法
我会传入变量来选择Dict Level和Key等一旦它正常工作
更新
let level1Dict:AnyObject = defaults.objectForKey("Level1")!.mutableCopy()
level1Dict.setValue(1, forKey: "moves")
defaults.setObject(level1Dict, forKey: "Level1")
答案 0 :(得分:1)
从用户默认值返回的字典是不可变的,因此您需要制作一个可变副本才能编辑它:
let level1Dict:AnyObject = defaults.objectForKey("Level1")!.mutableCopy()
另请注意,编辑字典不会自动更新用户默认值,您需要为键设置新字典(以替换旧设置的完整字典)。