Inserting data into realm DB with progress?

醉酒当歌 提交于 2019-12-02 08:31:07

Supposing you have a label for do this.
Ok.
Supposing you using MVVM pattern too.
Ok.

ViewController has label and "observe"(*) the ViewModel property 'progress'
ViewModel has property 'progress'

class ViewModel: NSObject {

  dynamic var progress: Int = 0

  func save(object object: Object) {
      do {
          let realm = try Realm()
          try realm.write({ () -> Void in
              // Here your operations on DB 
              self.progress += 1
          })
      } catch let error as NSError {
          ERLog(what: error)
      }
  }
}

In this way viewController is notified when "progress" change and you can update UI.

Your VC should have a method like this, called by viewDidLoad for instance:

private func setupObservers() {
   RACObserve(self.viewModel, keyPath: "progress").subscribeNext { (next: AnyObject!) -> Void in
     if let newProgress = next as? Int {
        // Here update label            
     }
   }
}

Where RACObserve is a global function:

import Foundation
import ReactiveCocoa

func RACObserve(target: NSObject!, keyPath: String) -> RACSignal  {
    return target.rac_valuesForKeyPath(keyPath, observer: target)
}

(*) You can use ReactiveCocoa for instance.

Katsumi from Realm here. First, Realm has no way to know the total amount of data. So calculating progress and notifying it should be done in your code.

A total is a count of results array. Store count as a local variable. Then define progress variable to store the number of persisted. progress should be incremented every save an object to the Realm. Then notify the progress.

let count = results.count // Store count of results
if count > 0{
    if let users = results.array {
        let progress = 0 // Number of persisted

        let realm = try! Realm()
        try realm.write {
            for user in users{
                let userList=UserList()
                [...]
                realm.add(userList,update: true)

                progress += 1 // After save, increment progress
                notify(progress, total: count)
            }
        }
    }
}

So there are several ways to notify the progress. Here we use NSNotificationCenter for example:

func notify(progress: Int, total: Int) {
    NSNotificationCenter
        .defaultCenter()
        .postNotificationName("ProgressNotification", object: self, userInfo: ["progress": progress, "total": total])
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!