大尺寸json的Realm数据插入耗时超过7分钟 [英] Realm data Insertion took over 7mins for big size json

查看:113
本文介绍了大尺寸json的Realm数据插入耗时超过7分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Alamofire下载大约7MB的大json数据,并使用RealmSwift将数据存储在realmobject和SwiftyJSON进行解析。下载完json后,我的领域对象插入似乎真的很慢插入。错误的代码?请指导我。

I use Alamofire to download big json data which was about around 7MB and use RealmSwift to store data at realmobject and SwiftyJSON to parse.My realm object insertion after it finished download the json seems really slow at insertion.Was something wrong with my bad code?Please guide me.

首先,我将展示最简单的Json:

First of all I will show simplest Json :

{
    {
        "Start" : "40000",
        "End" : "1000000",
        "Name" : "Smith",
        "Address" : "New York"
    },{...},more than 7000 records...
}

这是我的AlamofireAPI协议

Here is my AlamofireAPI Protocol

import Foundation
import Alamofire
import SwiftyJSON

protocol RequestDataAPIProtocol{
    func didSuccessDownloadingData(results:JSON,statusCode : Int)
    func didFailDownloadingData(err : NSError)
}

class RequestDataAPI{

var delegate : RequestDataAPIProtocol
init(delegate: RequestDataAPIProtocol){
    self.delegate=delegate
}

func post(requestURL:String,param:[String:String]){
    Alamofire.request(.GET, requestURL, parameters: param)
        .validate(statusCode: [200,500])
        .responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) -> Void in
            if let error = response.result.error {
                self.delegate.didFailDownloadingData(error)
            } else if let jsonObject: AnyObject = response.result.value {
                let json = JSON(jsonObject)
                self.delegate.didSuccessDownloadingData(json,statusCode: (response.response?.statusCode)!)
            }
        })
}

func doRequestSiteData(token : String){
    post(REQUEST_DATA,param:["data":"All","token":token])
}

}

这是我的Realm DB Helper

Here is my Realm DB Helper

import Foundation
import RealmSwift

class DBHelper{

func insertUserData(list: UserList){
    do {
        let realm = try! Realm()
        try realm.write({ () -> Void in
            realm.add(list,update: true)
        })
    } catch let error as NSError {
        print("Insert Error : \(error)")
    }
}
}

这是我的领域模型对象

import Foundation
import RealmSwift

class UserList: Object {

     dynamic var start : String = ""
     dynamic var end : String = ""
     dynamic var name : String = ""
     dynamic var address : String = ""

}

最后的代码,视图控制器,

And Final Code,View Controller,

class ViewController : UIViewController , RequestDataAPIProtocol{
       var dbHelper = DBHelper()
       var requestDataAPI : RequestDataAPI!

       override func viewDidLoad() {
           super.viewDidLoad()
           requestDataAPI = RequestDataAPI(delegate : self)
       }

       override func viewDidAppear(animated : Bool){
            //assume there is one token to request data
            requestDataAPI.doRequestSiteData(token)
       }

       func didSuccessDownloadingData(results: JSON, statusCode: Int){
        dispatch_async(dispatch_get_main_queue(), {
            print("Downloaded JSON")
            switch statusCode{
            case 200 :
               if results.count > 0{
                   if let users = results.array {
                      for user in users{
                         let userList=UserList()
                         userList.start=user["Start"].stringValue
                         userList.end=user["End"].stringValue
                         userList.name=user["Name"].stringValue
                         userList.address =user["Address"].stringValue
                         self.dbHelper.insertUserData(userList)
                      }
                   }
               }
               // took about more than 7 mins
               print("Insertion Done")
               break

           case 500,401,400 :
               //TODO: 
           default : break
           }
        })
    }
}

我知道描述所有代码步骤确实很愚蠢,对于将json数据快速插入领域的工作流程,我会写得尽可能简单。

我只想让所有人都知道在处理这么多json数据以及插入数据时我的工作流程是好是坏。

I just want all to know about my working flow is good or bad when handling so many json data,and also insertion.

我问这的原因是数据插入大约需要7分钟以上的时间。

The reason why I am asking this was the data insertion took about more than 7 mins to finish.

所以,我真的需要帮助,

So,I really need help,to make optimize at my code.

任何指南?

UPDATE:我使用委托和RequestDataAPI的协议,我从JamesQueue教程中学到了这种风格,因为我还是初学者,他还在学习Swift。ViewController已更新。这是我的整个流程的详细信息,没有更多的代码了。优化。

UPDATE : I use Delegate and Protocol from RequestDataAPI which i learn that style from JamesQueue Tutorial because I am completely beginner who is still learning Swift.ViewController is updated.That is my whole process detail,no more code left.Editing my question or answer a new is appreciated for code optimizing.

推荐答案

insertUserData 方法方法在循环中多次打开事务。提交事务是有点昂贵的操作。

insertUserData method method opens transactions so many times in the loop. To commit transaction is a little bit expensive operation.

您可以尝试在循环外尝试打开/提交事务吗?
换句话说,在进入循环之前打开事务,并在循环结束后提交一次事务。类似于以下内容:

Can you try to put out to open/commit a transaction outside of the loop? In other words, open the transaction before entering the loop, and commits the transaction once after the end of the loop. Like the following:

if results.count > 0 {
    if let users = results.array {
        let realm = try! Realm()
        try realm.write {
            for user in users{
                let userList=UserList()
                userList.start=user["Start"].stringValue
                userList.end=user["End"].stringValue
                userList.name=user["Name"].stringValue
                userList.address =user["Address"].stringValue
                realm.add(userList,update: true)
            }
        }
    }
}

这篇关于大尺寸json的Realm数据插入耗时超过7分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆