如何使用 Realm 通知

How to use Realm notifications

我正在尝试使用 Realm 数据库在 OS X 中编写应用程序。在我的程序中,我需要等待 Realm 写入完成,然后调用一个新的 veiwcontroller。经过大量研究,似乎使用 Realm 的内置通知中心是合适的。根据 Realm 文档,格式应该像这样工作

let token = realm.addNotificationBlock { notification, realm in
    viewController.updateUI()
}

我知道这是一个 swift 闭包,但我不确定如何使用它。如果我把代码改成这个

let token = realm.addNotificationBlock { notification, realm in
   println("The realm is complete")
}

写入完成后会打印到我的调试屏幕吗?或者更简单地说,如何仅在收到通知后才执行某些代码?

如果我将上面的代码放在我的应用程序中,我在调试屏幕中看不到我的行,我只看到以下内容:

2015-07-31 16:08:17.138 Therapy Invoice[27979:2208171] RLMNotificationToken released without unregistering a notification. You must hold on to the RLMNotificationToken returned from addNotificationBlock and call removeNotification: when you no longer wish to receive RLMRealm notifications.

制作 notificationToken 伊娃:

var notificationToken: NotificationToken?


deinit{
    //In latest Realm versions you just need to use this one-liner
    notificationToken?.stop()

    /* Previously, it was needed to do this way
    let realm = Realm()
    if let notificationToken = notificationToken{
        realm.removeNotification(notificationToken)
    }
    */
}

override func viewDidLoad() {
    super.viewDidLoad()
    let realm = Realm()
    notificationToken = realm.addNotificationBlock { [unowned self] note, realm in
       self.tableView.reloadData()
    }
...
}

来自 Realm latest docs (3.0.1):

添加 notificationToken.invalidate() 以便从通知中注销。

详细信息:

  • notificationToken 声明为 class 变量

    var notificationToken: NotificationToken?
    
  • viewDidLoad()

    中设置notificationToken
    notificationToken = realm.observe { [unowned self] note, realm in
       self.tableView.reloadData()
    }
    
  • 取消注册viewWillDisappear(animated: Bool)

    中的通知
    notificationToken?.invalidate()
    

编辑笔记:

  1. notificationToken.stop() 已弃用。
  2. realm.addNotificationBlock...会导致如下错误:

    Value of type 'Realm' has no member 'addNotificationBlock'