Swift/Realm 仅在提供的数组中添加最后一个对象 (SwiftyJSON)

标签 swift realm

我一直在使用以下函数来尝试让我的代码保持干爽。除了 JSON 中的最后一个对象被添加到 Realm 之外,一切都完美无缺。 json 参数来自 alamofire 并由 SwiftyJSON 转换。

如果您添加 print(object) 它会显示 4 个对象。有谁知道为什么 Realm 只会保存我的 for 循环的最后一次迭代,而不会保存其他的?感谢您的帮助,我对这个失去了理智。

谢谢!

    /**
    Takes the json provided by *fetchData* to build and save a Realm object by mapping properties to DB attributes. This was built to follow a DRY approach rather than re-inventing the wheel everytime we have to populate our Realm database.

    - Parameters:
        - json: JSON pulled from the mobile API by using a call like *fetchData*.
        - withObject: A realm object (e.g. Module, Audience, Location) that is used throughout the function to build a saveable object.
        - propertyMap: A closure that maps the property value from the json object (in current itteration) to the property of the Realm object.
            - **property**: A tuple from SwiftyJSON
            - **object**: Used to map property from tuple into realm property.

    - Returns: Void

             Example
             ApplicationManager.parseJSON(JSON(locations), withObject: Location(), propertyMap: [
                 "title" : { property, object in newObject.setValue(property.1.string!,  forKey: "title")},
                 "id"    : { property, object in newObject.setValue(property.1.int!, forKey: "id")}
             ])
    */
    static func parseJSON(json: JSON, withObject: Object, propertyMap: [String: (property: (String, JSON), object: Object) -> ()]) {
    // Itterate over every object in the json and provide each object.
    let realm = self.buildRealm()        
    for object in json {
        realm.beginWrite()

        // Itterate over every object and provide each property.
        for property in object.1 {
            // Make sure the property in the JSON is actually in our property map.
            if let propertyMap = propertyMap[property.0] {
                // Execute the property map closure that will set the property.
                propertyMap(property: property, object: withObject)
            }
        }

        // Create the object.
        realm.add(withObject)

        // Commit to realm
        try! realm.commitWrite()
        realm.refresh()
    }
}

最佳答案

如果我理解您的要求 - 您想要调用 parseJSON,并让它创建多个 Object 实例,并使用一个将为每个实例设置属性的闭包。在这种情况下,您应该使用泛型传入 Object 子类类型,并在每次迭代时创建一个新实例。沿着:

class func parseJSON<T: Object>(json: JSON, withType: T.Type, propertyMap: [String: (property: (String, JSON), object: Object) -> ()]) {
    let realm = try! Realm()
    try! realm.write({
        for object in json {
            let newObject = T()
            for property in object.1 {
                if let propertyMap = propertyMap[property.0] {
                    propertyMap(property: property, object: withObject)
                }
            }
            realm.add(newObject)
        }
    })
}

然后你这样调用它:

ViewController.parseJSON(JSON, withType: MyClass, propertyMap: myPropertyMap) 

关于Swift/Realm 仅在提供的数组中添加最后一个对象 (SwiftyJSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35027789/

相关文章:

swift - 开发 macOS 的辅助应用程序,apiDisabled

ios - 无法在 iPad 上打开 Playground Book

android - 使用 Realm 获取致命信号 11 (SIGSEGV),代码 1

swift - 使用主键列表过滤从 Realm 查询多个对象

swift - 如何在不使用 do .count 的情况下从结果中一一获取对象

Swift for var list.enumerated()

xcode - 快速 UITableView 设置 rowHeight

ios - KeyboardWillShowNotification 和 UIAlert

sqlite - 有什么方法可以将 Realm 数据库文件转换为 sqlite?

ios - Realm `description` 属性与其他属性的行为不同