[英]setObject:forKey: mutating method sent to immutable object
What am I missing...? 我想念什么...?
elsewhere in my project there is code like this: 我项目的其他地方有这样的代码:
let allUsers = ["userName":["difficulty": 1, "highscore": 50],"userName2":["difficulty": 2, "highscore: 75]]
defaults.setObject(allUsers, forKey: "allUsers")
I want to change a value for one user in that array of users: 我想为该用户数组中的一个用户更改值:
var allUsers = defaults.objectForKey("allUsers") as! [String:NSMutableDictionary]
let changingUser = allUsers["userName"]! as NSMutableDictionary
Neither of these will work: 这些都不起作用:
changingUser.setObject(3, forKey: "difficulty")
changingUser["difficulty"] = 3
with the error: 与错误:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object' ***由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“-[__ NSCFDictionary setObject:forKey:]:发送给不可变对象的变异方法”
You can't just cast a NSDictionary
to a NSMutableDictionary
. 您不能只是将NSDictionary
转换为NSMutableDictionary
。 You can initialize one by passing in an immutable counterpart, but unfortunately that isn't a deep mutable structure. 您可以通过传递一个不变的对应对象来初始化一个对象,但是不幸的是,这并不是一个深层的可变结构。
However, you can cast it to a Swift Dictionary and assign it to a var: 但是,您可以将其转换为Swift字典并将其分配给var:
var allUsers = defaults.objectForKey("allUsers") as? [String: [String: Int]] ?? [:]
allUsers2["userName"]?["difficulty"] = 3
But note that Swift dictionaries are value objects and have value semantics. 但是请注意,Swift字典是值对象,并且具有值语义。 That is, if you do this in steps like so: 也就是说,如果您按照以下步骤进行操作:
var allUsers = defaults.objectForKey("allUsers") as? [String: [String: Int]] ?? [:]
changingUser = allUsers["userName"]
changingUser?["difficulty"] = 3 //mutates a copy
This will not work, since changingUser
is a copy and while writing to it, does mutate it, it doesn't mutate the allUsers
dictionary. 这是行不通的,因为changingUser
是一个副本,在写它,做它发生变异,它并没有发生变异的allUsers
字典。 So you have to either write the changed inner dict back into the outer dict, or do as I did above. 因此,您必须将更改后的内部dict写回到外部dict,或者按照我上面的方法进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.