Adding an array of Json Data to Realm












0















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?



P.S
"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










share|improve this question

























  • accessing realm and writing or adding objects takes most of the time as far as I know. So I would suggest don't do it in the for loop, store all of the objects in an array and add the array to realm after the for loop.

    – hardik parmar
    Nov 19 '18 at 14:12











  • thank you @hardikparmar yeah it also works this way but I want to completely remove the for loops

    – Omar AlQasmi
    Nov 21 '18 at 9:03
















0















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?



P.S
"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










share|improve this question

























  • accessing realm and writing or adding objects takes most of the time as far as I know. So I would suggest don't do it in the for loop, store all of the objects in an array and add the array to realm after the for loop.

    – hardik parmar
    Nov 19 '18 at 14:12











  • thank you @hardikparmar yeah it also works this way but I want to completely remove the for loops

    – Omar AlQasmi
    Nov 21 '18 at 9:03














0












0








0








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?



P.S
"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










share|improve this question
















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?



P.S
"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







ios swift realm swifty-json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 12:25









Dávid Pásztor

22.7k83152




22.7k83152










asked Nov 18 '18 at 6:30









Omar AlQasmiOmar AlQasmi

12




12













  • accessing realm and writing or adding objects takes most of the time as far as I know. So I would suggest don't do it in the for loop, store all of the objects in an array and add the array to realm after the for loop.

    – hardik parmar
    Nov 19 '18 at 14:12











  • thank you @hardikparmar yeah it also works this way but I want to completely remove the for loops

    – Omar AlQasmi
    Nov 21 '18 at 9:03



















  • accessing realm and writing or adding objects takes most of the time as far as I know. So I would suggest don't do it in the for loop, store all of the objects in an array and add the array to realm after the for loop.

    – hardik parmar
    Nov 19 '18 at 14:12











  • thank you @hardikparmar yeah it also works this way but I want to completely remove the for loops

    – Omar AlQasmi
    Nov 21 '18 at 9:03

















accessing realm and writing or adding objects takes most of the time as far as I know. So I would suggest don't do it in the for loop, store all of the objects in an array and add the array to realm after the for loop.

– hardik parmar
Nov 19 '18 at 14:12





accessing realm and writing or adding objects takes most of the time as far as I know. So I would suggest don't do it in the for loop, store all of the objects in an array and add the array to realm after the for loop.

– hardik parmar
Nov 19 '18 at 14:12













thank you @hardikparmar yeah it also works this way but I want to completely remove the for loops

– Omar AlQasmi
Nov 21 '18 at 9:03





thank you @hardikparmar yeah it also works this way but I want to completely remove the for loops

– Omar AlQasmi
Nov 21 '18 at 9:03












1 Answer
1






active

oldest

votes


















0














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 ^_^






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53358459%2fadding-an-array-of-json-data-to-realm%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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 ^_^






    share|improve this answer






























      0














      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 ^_^






      share|improve this answer




























        0












        0








        0







        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 ^_^






        share|improve this answer















        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 ^_^







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 22 '18 at 15:07









        rmaddy

        246k27327390




        246k27327390










        answered Nov 22 '18 at 0:22









        Omar AlQasmiOmar AlQasmi

        12




        12
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53358459%2fadding-an-array-of-json-data-to-realm%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

            ComboBox Display Member on multiple fields

            Is it possible to collect Nectar points via Trainline?