Realm data Insertion took over 7mins for big size json

ⅰ亾dé卋堺 提交于 2019-12-06 20:38:30

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)
            }
        }
    }
}

I have fixed slow insertion issue by using this code.

func addAsBatch<T: Object>(_ data: [T]) {
    if !isRealmAccessible() { return }

    let realm = try! Realm()
    realm.refresh()

    realm.beginWrite()
    for object in data {
        realm.add(object)
    }
    try? realm.commitWrite()
}

Showing function use with your example -

let userList = UserList()
userList.start = user["Start”].stringValue
userList.end = user[“End”].stringValue
userList.name = user[“Name”].stringValue
userList.address  = user[“Address”].stringValue

addAsBatch(userList)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!