ios - 我可以在 Realm for Swift 中将 RealmObject 序列化为 JSON 或 NSDictionary 吗?

标签 ios swift realm

我正在测试 Realm,但找不到将我的对象转换为 JSON 的简单方法。 我需要将数据推送到我的 REST 接口(interface)。 我怎样才能使用 swift 做到这一点?

class Dog: Object {
  dynamic var name = ""
}

class Person : Object {
  dynamic var name = ""
  let dogs = List<Dog>()
}

我正在尝试这样的事情,但我无法迭代未知对象(列表)

extension Object {
  func toDictionary() -> NSDictionary {
    let props = self.objectSchema.properties.map { $0.name }
    var dicProps = self.dictionaryWithValuesForKeys(props)

    var mutabledic = NSMutableDictionary()
    mutabledic.setValuesForKeysWithDictionary(dicProps)

    for prop in self.objectSchema.properties as [Property]! {

      if let objectClassName = prop.objectClassName  {
        if let x = self[prop.name] as? Object {
          mutabledic.setValue(x.toDictionary(), forKey: prop.name)
        } else {
          //problem here!
        }
      }
    }
    return mutabledic
  }
}

**抱歉代码丑陋。

最佳答案

我也是 Realm 的新手,但我认为最简单的方法是反射(reflection) Object's schema :

class Person: Object {
    dynamic var name = ""
    dynamic var age = 0
}

let person = Person()

let schema = person.objectSchema

let properties = schema.properties.map() { $0.name }

let dictionary = person.dictionaryWithValuesForKeys(properties) // NSDictionary

println(properties)
println(dictionary)

关于ios - 我可以在 Realm for Swift 中将 RealmObject 序列化为 JSON 或 NSDictionary 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150087/

相关文章:

java - 代号 1 个 GPS 提供商和当前位置

ios - 关闭推送通知 ios

ios - 在 textField 集合中查找空的 textField

swift - 出现错误 : Use of unresolved identifier "LinkingObjects"

ios - Realm 过滤器 firstDate 旧于 newDate

ios - AppStore 更新和 Realm

ios - 用数组填充 UITableView 不起作用

ios - 如何在 SWIFT 中的表格单元格上分配两个 Segue?

ios - 基于约束的 collectionView 的不同单元格大小

arrays - Swift:将字符串中的单独字符与字典中的值匹配