ios - Swift NSMutableDictionary 删除对象

标签 ios swift nsmutabledictionary

我有一个像这样启动的 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/

相关文章:

ios - Xcode IB Storyboard方向和容器 View

objective-c - 将 NSString 与 NSString 分开

ios - HKHealthStore 类型的值没有类型 dateOfBirthWithError

objective-c - 循环 NSMutableDictionary

iphone - 在未知的 NSMutableArray 深度中搜索值

macos - MAC OS X NSMutableDictionary writeToFile 失败

ios - 如何在iOS中识别旋转手势的开始和结束?

ios - NS_ENUM 和 NS_OPTIONS 有什么区别?

ios - iOS 13 更新后 iCloud UIDocument 打开失败

swift - 动态编程变量初始化