I am using Realm and trying to reorder cells in my TableView. Behaviour that I find odd is that it works sometimes exactly like I want (it updates the data in Realm properly) but sometimes when it hits the line:
myRealm.write {
it does not go inside this block. Using breakpoints I can see it skips the whole block and goes directly to the end of this block. Because of this, even-though it gives the visual appearance that the tableView has been re-ordered, it has not been re-ordered in Realm.
I should note that I am using a column in a table in Realm called order as a means of storing order. Also, labels is the array from Realm of the Table that I am trying to order
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
//update when you move a row up
if sourceIndexPath.row > destinationIndexPath.row {
let lowerbound = destinationIndexPath.row
let upperbound = sourceIndexPath.row
do{
let myRealm = try Realm()
myRealm.write {
let labelAtSource = self.labels![upperbound]
labelAtSource.order = lowerbound
for i in lowerbound...upperbound-1{
let label = self.labels![i]
label.order = i+1
}
}
}catch { }
}else{ //when you move a row down
let lowerbound = sourceIndexPath.row
let upperbound = destinationIndexPath.row
do{
let myRealm = try Realm()
myRealm.write {
let labelAtSource = self.labels![lowerbound]
labelAtSource.order = upperbound
for i in lowerbound+1...upperbound{
let label = self.labels![i]
label.order = i-1
}
}
}catch { }
}
}
You're calling a throwing initializer Realm()
in a do-catch block without any error handling at all. I'd guess that this fails. Instead of catching the error and let it disappear unhandled, I'd rather recommend to use try!
, which would cause a runtime error here.
But then you should also ensure that you have accessed your Realm before at least once initially to avoid having to worry about failing schema migrations / validations at this point. Most errors which can still occur later with the default realm setup are typically only seen during development, eg when the Browser is attached to the simulator files.
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.