How to use Realm notifications

I am trying to write an application in OS X using the Realm database. In my program, I need to wait until the recording in Realm is complete, and then call the new controller. After much research, it seems that using Realm, built in the notification center, would be appropriate. According to Realm documentation, the format should work as follows

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

I understand this is a quick close, but I'm not sure how to use it. If I changed the code to this

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

Will it print on my debug screen when recording is completed? Or easier, how can I execute the code only after receiving a notification?

If I put the above code in my application, I don’t see my line on the debug screen, I see the following:

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

+5
source share
2 answers

Make notificationToken ivar:

 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() } ... } 
+6
source

From Realm latest docs (3.0.1):

Add notificationToken.invalidate() to unregister the notification.

In detail:

  • Declare a notificationToken class variable as

     var notificationToken: NotificationToken? 
  • Set notificationToken to viewDidLoad()

     notificationToken = realm.observe { [unowned self] note, realm in self.tableView.reloadData() } 
  • viewWillDisappear(animated: Bool) from notification in viewWillDisappear(animated: Bool)

     notificationToken?.invalidate() 

Edit notes:

  • notificationToken.stop() deprecated.
  • realm.addNotificationBlock... will result in the following error:

    A value of type 'Realm' does not have an addNotificationBlock element '

+7
source

All Articles