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

时间:2016-01-27 02:29:55

标签: swift realm

我有以下功能,我一直在尝试保持我的代码DRY。除了只有JSON中的最后一个对象被添加到Realm之外,一切都运行良好。 json param来自alamofire并由SwiftyJSON转换。

如果添加print(对象),它会显示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()
    }
}

1 个答案:

答案 0 :(得分:0)

如果我理解你的后续内容 - 你想调用parseJSON,并让它创建多个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) 

然后你称之为:

('weirdly', 'talking')