【问题标题】:How to convert NSManagedObject to NSDictionary如何将 NSManagedObject 转换为 NSDictionary
【发布时间】:2015-04-16 06:44:01
【问题描述】:

我正在尝试将 NSManagedObject 转换为 NSDictionary 这是我尝试过的:

var keys:NSArray = order?.entity.attributesByName.keys
var dict:NSDictionary = order?.dictionaryWithValuesForKeys(keys)

但我得到错误:

 LazyForwardCollection<MapCollectionView<Dictionary<NSObject,
 AnyObject>, NSObject>>? is not convertible to NSArray.

我在这里做错了什么?

【问题讨论】:

  • 你需要NSDictionary或者如果你有swift Dictionary就可以了?
  • 我不知道。我的目标是将该字典转换为 JSON 字符串。因此,如果我可以用字典做到这一点,那我就没有问题了。

标签: ios swift core-data nsdictionary nsmanagedobject


【解决方案1】:

字典的keys 属性返回一个LazyForwardCollection,它必须被转换为一个真正的数组。

另一个问题是order 显然是可选的,所以它需要 被打开,例如带有可选绑定。

if let theOrder = order {
    let keys = Array(theOrder.entity.attributesByName.keys)
    let dict = theOrder.dictionaryWithValuesForKeys(keys)
} else {
    // order is nil
}

【讨论】:

  • 我不知道。我正在使用 swift 1.2。我需要添加参数名称,但第二行无法通过:let keys = Array(arrayLiteral: order?.entity.attributesByName.keys) let dict = order?.dictionaryWithValuesForKeys(keys)
  • @1110:我目前无法访问 Xcode 6.3,所以我用 6.2 对其进行了测试。我没想到这段代码会有所不同,但这可能是错误的。我可以稍后使用 Xcode 6.3 检查。很抱歉,如果这造成了混乱。
  • 是的,我复制了它,但它不起作用。我不明白这应该是很简单的事情:(
  • @1110:查看更新的答案(现在使用 Xcode 6.3/Swift 1.2 检查)。
  • @MartinR 即使这样可行,我仍然无法将它们序列化为 Json,NSJsonSerialization.isValidObject 仍然返回 false。有任何想法吗?你最终让它发挥作用了吗?
【解决方案2】:

您可以将resultType 上的NSFetchRequest 设置为DictionaryResultType,而不是将对象作为NSManagedObjects 从数据库中取出,以便在执行请求时返回字典。

但是,您将无法编辑这些字典中的值并将更改保存在您的数据库中。如果您只需要从数据库中读取数据,那么这不是问题。

【讨论】:

    【解决方案3】:

    不优雅,但这应该可以......

    var names = Array<String>()
    for attributeName in order?.entity.attributesByName.keys
    {
        names.append(attributeName as! String)
    }
    

    这是一个将某种集合转换为另一个集合的问题,即使内部类型相同,这也绝非易事。

    编辑: 快一点的精神

    var names = map(order?.entity.attributesByName.keys){return $0 as! String}
    

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      相关资源
      最近更新 更多