正在跳过Realm.write

时间:2015-07-10 05:46:18

标签: ios realm

我正在使用Realm并尝试重新排序TableView中的单元格。我觉得很奇怪的行为是它有时完全像我想要的那样工作(它正确地更新了Realm中的数据),但有时当它碰到这一行时:

myRealm.write {

它不会进入这个区块。使用断点我可以看到它跳过整个块并直接进入该块的末尾。因此,即使它给出了已经重新排序tableView的视觉外观,它仍未在Realm中重新排序。

我应该注意到我在Realm中的一个表中使用了一个名为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 { }
        }
}

1 个答案:

答案 0 :(得分:0)

您正在do-catch块中调用throw initializer Realm()而根本没有任何错误处理。我猜这个失败了。 我并不建议使用try!而不是捕获错误并让它消失未处理,这会导致运行时错误。

但是,您还应确保至少在最初之前访问过您的Realm,以避免在此时担心架构迁移/验证失败。以后使用默认域设置仍然可能发生的大多数错误通常仅在开发期间出现,例如,当浏览器附加到模拟器文件时。

相关问题