我有一个像这样启动的 NSMutableDictionary
var data = NSMutableDictionary()
稍后我试图删除该值,因为我想将每个值向上移动一个键。这是我正在做的代码
let buttonRow = sender.tag
let setCount = buttonRow + 1
var keyedPath: String = NSString(format: "Set%d", setCount) as String
let value: AnyObject? = data.valueForKey(keyedPath)
var goodSetsCount: String = NSString(format: "Set%d", goodSets.count) as String
goodSets.setValue(value, forKey: goodSetsCount)
//data.setValue("Hello", forKey: keyedPath)
//data.removeObjectForKey(keyedPath)
在注释掉的两行我都得到了这个错误
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
如果您能帮我找到错误或删除对象并将它们移到字典中的方法,我们将不胜感激。
最佳答案
默认情况下,NSJSONSerialization.JSONObjectWithData
返回不可变容器。您需要指定选项 NSJSONReadingOptions.MutableContainers
才能检索可变容器。事实上,在 Swift 1.2 中你的任务
data = NSJSONSerialization.JSONObjectWithData(returnData, options: nil, error: &jsonError) as! NSMutableDictionary
应该抛出一个运行时异常,因为您正在使用强制向下转换为 NSMutableDictionary,这将失败,尽管我不确定 Cocoa 类是否强制执行此操作。
如果您将行更改为
data = NSJSONSerialization.JSONObjectWithData(returnData, options: .MutableContainers, error: &jsonError) as! NSMutableDictionary
您的代码应该可以工作。
关于ios - Swift NSMutableDictionary 删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29665100/