Realm-cocoa: Realm Results aren't updated if there's a NotificationToken observing the Results

Created on 26 Aug 2020  路  3Comments  路  Source: realm/realm-cocoa

In trying to replicate #6709 I'm running into what might be a related issue. This code should work, right?

Expected Results

Realm Results is up-to-date after adding new object

Actual Results

Realm Results is not updated after adding a new object when observing for changes via NotificationToken

Steps for others to Reproduce

  1. Open provided project RealmTest.zip
  2. Run pod install
  3. Run the app
    Result: App crashes due to trying to access just added object in Results

Code Sample

class ViewController: UIViewController {

    private var markers: Results<SongMarker>?
    private var markersChangeTableUpdateNotificationToken: NotificationToken?

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonString = "[{\"organizationShows\":[{\"id\":\"7f5cdcfa-5ff6-11ea-9e98-22000b74e21e\",\"songs\":[{\"id\":\"91a01616-6d1b-11ea-ae0e-22000b74e21e\"},{\"id\":\"09d141c8-5ff7-11ea-8c8f-22000b74e21e\"}]}],\"id\":\"00000000-5ab5-1de9-f4d1-b6b91ed1b036\"}]"
        let jsonData = jsonString.data(using: .utf8)!
        let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! [[String: Any]]

        DataModel.shared.importFromJSON(jsonObject)

        let song = DataModel.shared.realm!.object(ofType: Song.self, forPrimaryKey: "91a01616-6d1b-11ea-ae0e-22000b74e21e")!

        markers = DataModel.shared.realm?.objects(SongMarker.self).filter("ANY songs.id = %@", song.id).sorted(by: [SortDescriptor(keyPath: "time"), SortDescriptor(keyPath: "createdAt", ascending: false)])

        //commenting these out fixes it
        markersChangeTableUpdateNotificationToken?.invalidate()
        markersChangeTableUpdateNotificationToken = markers?.observe { changes in
        }

        markers?.realm?.beginWrite()

        let marker = SongMarker()
        song.markers.insert(marker, at: 0)

        print(markers?[0])
    }

}

Version of Realm and Tooling

Realm framework version: 5.3.5

Realm Object Server version: ?

Xcode version: 11.6

iOS/OSX version: iOS 13.6

Dependency manager + version: CocoaPods 1.9.3

O-Community T-Bug

All 3 comments

It looks like the specific circumstances that are broken are:

  1. It must be the first access of the Results
  2. There must be a notifier, and the initial run of the async query needs to have completed
  3. The access must be inside a write transaction following a change which should have invalidated the async query results.

Should be easy to fix.

Should this be resolved in version 5.4.0? I continue to see this crash.

I forgot to actually bump the submodule pointer to pull it in. It'll be in the next release.

Was this page helpful?
0 / 5 - 0 ratings