I am currently developing an application, and I am facing some problems I can not solve.
I currently have two views:
My problem is that, after adding a new object to my Realm database and immediately returning to the first view, sometimes the tableView
does not recognize the newly added object but sometimes it does.
I hope this is information enough - ask me questions if needed.
override func viewWillAppear(_ animated: Bool) {
setupDataForViewTable()
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
}
func setupDataForViewTable() {
let realmm = try! Realm()
let cryptocurrenciesFromDatabase = realmm.objects(crypto.self)
for crypto in cryptocurrenciesFromDatabase{
//For debugging
if crypto.name.count <= 0{
continue
}
let ROI = 0.0
let change24h = 0.0
let totalHolding = Double(crypto.buyingPrice) * Double(crypto.amount)
cryptoCurrencies.append((name : crypto.name, amount : crypto.amount, ROI : ROI, change24h : change24h, total : totalHolding))
}
}
Then there is the code from the second view, where i add stuff:
func updateCryptoInRealmDatabase(name : String, buyingPrice : Double, amount : Double){
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
let objectToUpdate = realm.objects(crypto.self).filter("name CONTAINS %@", name).first
try! realm.write {
objectToUpdate!.buyingPrice = (objectToUpdate!.buyingPrice + buyingPrice) / 2
objectToUpdate!.amount += amount
}
}
}
}
You need to make sure that tableView is updated when you navigate back to the first view. If that view is holding reference to Realm object and second view edited List
in that object then it is enough to reload table. If you are holding reference to query of Realm objects then it will be refreshed automatically by Realm after commit update.
You can simply reload the view after it is shown again or register for Realm notifications and update the view as the second view does changes to it.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
If first view showing (same) Realm object that second view is editing then data is already up to date. We will get fresh count of related objects here:
func titleTableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return realmObject.relatedObjects.count
}
Update: Fixed refresh need for Realm Result
and added link to notifications in Realm documentation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.