gpt4 book ai didi

ios - 后台异步来自 JSON 的 Realm

转载 作者:可可西里 更新时间:2023-11-01 01:27:09 25 4
gpt4 key购买 nike

我想在后台异步地从 JSON 编写 Realm,但我不明白为什么我的代码不能正常工作。

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

所以,我想在后台等待完全写入数据库(例如,显示进度 View )然后进行下一步。

最佳答案

您必须检查 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
}

关于ios - 后台异步来自 JSON 的 Realm ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40977288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com