2016-12-05 33 views
2

異步我想工作,在後臺異步從JSON寫的境界,但我不明白爲什麼我的代碼是不是必須工作。境界在後臺

override func viewDidLoad() { 
    super.viewDidLoad() 

    myFunc() 

} 

和myFunc的():

func myFunc() { 

     let realm = try! Realm() 

     // get file JSON from local device and write data from it to RealmDB 
     if realm.isEmpty { 

      //local file JSON 
      let file = Bundle.main.path(forResource: "file", ofType: "json")! 
      let url = URL(fileURLWithPath: file) 
      let jsonData = NSData(contentsOf: url)! 

      //Serialization JSON 
      let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: []) 


      DispatchQueue.main.async { 

      realm.beginWrite() 

      //Create data from JSON to our objects 
      realm.create(DataRoot.self, value: json, update: true) 

      try! realm.commitWrite() 

      } 
     } 
    } 

DB創造,但下一步(因爲我看到)是錯誤的:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

     return (transport.filter("id == 1").first?.routes.count)! 
    } 

所以,我想等待在後臺完整寫入數據庫(例如顯示進度視圖)並轉到下一步。

回答

1

你必須檢查在numberOfRows方法可選的,做這樣的

func myFunc() { 
     let queue1 = DispatchQueue(label: "com.appname.queue") 
     queue1.async { 
      let realm = try! Realm() 
      // get file JSON from local device and write data from it to RealmDB 
      if realm.isEmpty { 

       //local file JSON 
       let file = Bundle.main.path(forResource: "file", ofType: "json")! 
       let url = URL(fileURLWithPath: file) 
       let jsonData = NSData(contentsOf: url)! 

       //Serialization JSON 
       let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: []) 
       realm.beginWrite() 

       //Create data from JSON to our objects 
       realm.create(DataRoot.self, value: json, update: true) 

       try! realm.commitWrite() 

       DispatchQueue.main.async { 

        self.tableview.reloadData() 

       } 

      } 
     } 
    } 


    override func tableView(_ tableView: UITableView,  numberOfRowsInSection section: Int) -> Int { 
     if let routes = transport.filter("id == 1").first?.routes { 
      return routes.count 
     } 
      return 0 
    } 
1

一般回答你的問題:高級別領域的功能,你想在這裏使用是notifications

您應該以這樣一種方式構建您的應用程序,以便您希望用於備份視圖控制器的數據可以用Realm查詢或通知表示,以便在視圖或控制器的基礎數據發生變化時可以執行相關的視圖更新操作。

還有一些其他的問題,你的代碼,例如潛在從不同的線程比它創建一個訪問Realm實例。我建議你在Realm's Threading documentation閱讀更多關於這個。