Dan DeLuca Dan DeLuca - 5 months ago 39
Swift Question

How to use Realm notifications, in Swift

I am trying to write an application in OS X using a Realm database. In my program I need to wait for a Realm write to be complete then call up a new veiwcontroller. After much research it seems that using Realm's built in notification center would be appropriate. According to the Realm documentation the format should work like this

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


I understand that this is a swift closure, but I am 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")
}


Would that print to my debugging screen when the write is complete? Or more simply how do I execute some code only after I receive the notification?

If I place the above code in my app I do not see my line in the debug screen all I see is the following.

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 recieve RLMRealm notifications.

Answer

Make notificationToken an ivar:

var notificationToken: NotificationToken?

deinit{
    let realm = Realm()
    if let notificationToken = notificationToken{
        realm.removeNotification(notificationToken)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let realm = Realm()
    notificationToken = realm.addNotificationBlock { note, realm in
       println("The realm is complete")
    }
...
}