我一直在使用此扩展程序将我的领域结果成功映射到NSDictionary:

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

    let mutabledic = NSMutableDictionary()
    mutabledic.setValuesForKeysWithDictionary(dictionary)

    for prop in self.objectSchema.properties as [Property]! {
        // find lists
        if let nestedObject = self[prop.name] as? Object {
            mutabledic.setValue(nestedObject.toDictionary(), forKey: prop.name)
        } else if let nestedListObject = self[prop.name] as? ListBase {
            var objects = [AnyObject]()
            for index in 0..<nestedListObject._rlmArray.count  {
                let object = nestedListObject._rlmArray[index] as AnyObject
                objects.append(object.toDictionary())
            }
            mutabledic.setObject(objects, forKey: prop.name)
        }
    }
    return mutabledic
}
}

但是我现在正在尝试映射:
let allObjectLists = realm.objects(UseItemList.self)
let firstObject  = allObjectLists[0].valueForKey("useItems")
let toDict = firstObject?.toDictionary() //error here

如何解决此问题,必须有一种方法可以将allObjectLists[0].valueForKey("useItems")映射到字典

这是我得到的错误:
2016-11-10 11:45:09.056 CPS Stocker[6187:167500] -[_TtGC10RealmSwift4ListC11CPS_Stocker7UseItem_ toDictionary]: unrecognized selector sent to instance 0x7fa7f3a49650
2016-11-10 11:45:09.253 CPS Stocker[6187:167500] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_TtGC10RealmSwift4ListC11CPS_Stocker7UseItem_ toDictionary]: unrecognized selector sent to instance 0x7fa7f3a49650'

这是我的UseItemList Object类:
class UseItemList: Object {
  dynamic var dateCreated = NSDate()
  dynamic var locationUnique = Int()
  dynamic var MainActivityReference1 = ""
  dynamic var MainActivityReference2 = ""
  let useItems = List<UseItem>()
}

最佳答案

您不在此处访问Object

该行代码let firstObject = allObjectLists[0].valueForKey("useItems")正在拉出useItems对象,该对象是List对象。这就是为什么它报告没有可用的名为toDictionary()的方法的原因。

如果您要获取useItems中的第一个对象以根据该对象生成字典,则应为:

let allObjectLists = realm.objects(UseItemList.self) // Get all 'UseItemList' objects from Realm as a `Results` object
let firstObjectInList  = allObjectLists.first! // Get the first UseItemList object from the 'Results' object
let useItemsInFirstObject = firstObjectInList.useItems // Access the 'useItems' List object in the first object
let firstUseItem = useItems.first! // Access the first item from the 'useItems' List object
let toDict = firstItem.toDictionary() // Convert the first item into an array

显然,您可以将其压缩为一行代码,但是您需要确保以正确的顺序访问所有元素,否则最终将无法获得正确的Object。 :)

10-08 05:30