我正在测试 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/