iOS中的RealmSwift问题与'write'块

时间:2015-09-18 20:13:05

标签: ios swift2 realm

我还有一个关于写块的问题 - 'SharedRealm.realm.write()' - 错误 - “调用可以抛出,但它没有标记为'try'并且错误未被处理”,它是怎么回事处理。

这是代码:

func addItems(items:[Item]) {
    do {
        let rlm = try Realm()

        rlm.write { () -> Void in
            for item in items {
                rlm.add(item, update: true)
            }
        }
    }
    catch let rlmError {
        print("Realm() generated error: \(rlmError)")
    }
}

我仍然得到同样的错误 - “:13:电话可以投掷,但没有标记'尝试'”

2 个答案:

答案 0 :(得分:1)

由于Realm()可能会抛出错误,因此您需要将其包装在do {try} catch块中

extension Realm {

    public class func saveClosure(dbClosure: (Realm)->()) {
        do {
            let rlm = try Realm()
            rlm.write { () -> Void in
                dbClosure(rlm)
            }

        }
        catch let rlmError{
            print("Realm() generated error: \(rlmError)")
        }
    }
}

结帐https://gist.github.com/edwardIshaq/b5810ab35c30df10af24

答案 1 :(得分:1)

private void CountTicket() { try { int count = 3; Component[] components = PanelSeat.getComponents(); for (int i = 0; i < components.length; i++) { if (components[i] instanceof JButton) { if (((JButton) components[i]).isSelected()) { // I wanna check if any button is clicked by a user if (JOptionPane.showConfirmDialog(this, "Seat Confirmation") == JOptionPane.YES_OPTION) { // confirm message ((JButton) components[i]).setEnabled(false); // disable the button count--; System.out.println("Your ramaining seat : " + count); } } } } } catch (Exception e) { e.printStackTrace(); } } 可能会抛出错误以及初始值设定项,因此您需要在此调用前添加rlm.write { ... }运算符。