简体   繁体   中英

Adding an array of Json Data to Realm

I'm making an app for airports and I'm getting an array of data from one api, like so:

"data":[
{"id":"001","code":"ABZ","name":"Aberdeen","country":"United Kingdom"},
{"id":"002","code":"AUH","name":"Abu Dhabi","country":"United Arab Emirates"},
.
.
.
]

AND :

"airports":[
{"from":"001",
    "to":["1","3","11","13","12","20","23","27","29","31","33"]
},
.
.
.
]

I have created realm model classes:

class AirportsDataRealm: Object {
    @objc dynamic var name: String = ""
    @objc dynamic var id: Int = 0
    @objc dynamic var code: String = ""
    @objc dynamic var country: String = ""
    override static func primaryKey() -> String? {
        return "id"
    }
}

class AirportsFromToRealm: Object {
    @objc dynamic var fromID: Int = 0
    var toID = List<Int>()
    override static func primaryKey() -> String? {
        return "fromID"
    }
}

now I want to save it into realm, I'm using swiftyJSON and I have used for-loop to do it and it is working fine but I think it's taking long time since the array is very long, here is what I've done:

    // Airports Data
    let countData = json["data"].count
    for i in 0...countData - 1{
        let airportsDataModel = AirportsDataRealm()
        airportsDataModel.code = json["data"][i]["code"].stringValue
        airportsDataModel.name = json["data"][i]["name"].stringValue
        airportsDataModel.country = json["data"][i]["country"].stringValue
        airportsDataModel.id = Int(json["data"][i]["id"].stringValue)!
        try! realm.write {
            realm.add(airportsDataModel, update: true)
        }
    }

    //Airports FROM-TO
    let countFromTo = json["airports"].count

    for i in 0...countFromTo - 1{
        let fromToDataModel = AirportsFromToRealm()
        fromToDataModel.fromID = Int(json["airports"][i]["from"].stringValue)!
        let arrayTo = json["airports"][i]["to"].arrayValue.map{ $0.intValue }
        fromToDataModel.toID.append(objectsIn: arrayTo)

        try! realm.write {
            realm.add(fromToDataModel, update: true)
        }
    }

is there any way to save the whole array in realm in one shot without for-loop?

PS "there should be a relation between the two tables because each from 'id' has a list of 'to' id's and the id's are from the data table, for now I managed to create this relations when fetching the data using filters ,, so just ignore this"

Thank you

Simply use map method,

First I needed to add initializers to my object classes and pass json array as a parameter, like so:

class AirportsDataRealm: Object {
    @objc dynamic var name: String = ""
    @objc dynamic var id: Int = 0
    @objc dynamic var code: String = ""
    @objc dynamic var country: String = ""
    convenience required init(withJSON json : JSON) {
        self.init()
        self.name = json["name"].stringValue
        self.id = json["id"].intValue
        self.code = json["code"].stringValue
        self.country = json["country"].stringValue
    }
    override static func primaryKey() -> String? {
        return "id"
    }
}


class AirportsFromToRealm: Object {
    @objc dynamic var fromID: Int = 0
    var toID = List<Int>()
    convenience required init(withJSON json : JSON) {
        self.init()
        self.fromID = json["from"].intValue
        let toArray = json["to"].arrayValue.map{ $0.intValue }
        self.toID.append(objectsIn: toArray)
    }

    override static func primaryKey() -> String? {
        return "fromID"
    }
}

Then by using map method the code will look like this:

func updateAirport(json: JSON) {
        // Airports Data
        let airportsData : [AirportsDataRealm]
        let airportsDataJsonArray = json["data"].array
        airportsData = airportsDataJsonArray!.map{AirportsDataRealm(withJSON: $0)}
        //Airports FROM-TO
        let airportsFromTo : [AirportsFromToRealm]
        let airportsFromToJsonArray = json["airports"].array
        airportsFromTo = airportsFromToJsonArray!.map{AirportsFromToRealm(withJSON: $0)}
        //Write To Realm
        try! realm.write {
            realm.add(airportsData, update: true)
            realm.add(airportsFromTo, update: true)
        }
}

No for loops anymore ^_^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM