2 / 10
Feb 2021

I’ve been experimenting with the @ObservedRealmObject wrapper, and it’s been working fine for me in builds. However, it breaks down in the previews, either eventually crashing (when played) or not running at all.

For now I’ve been commenting them out when I need to see a simple preview, but is there a better way to go about it? I didn’t see any previews on ListSwiftUI (except ContentView, which wasn’t working)

Oh, ignore the

let realm = try ! Realm()

line, was experimenting and forgot to remove it.

Right now I’m just passing in an object into the view (normally I change the values, but it isn’t necessary for this example). I’m sure there’s a better way, but this does work without the @ObservedRealmObject.

Sample:

@objcMembers class Person: Object, ObjectKeyIdentifiable { var name = "no name" } struct PersonView: View { @ObservedRealmObject var person: Person let realm = try! Realm() var body: some View { Text(person.name) } } struct PersonView_Previews: PreviewProvider { static var previews: some View { PersonView(person: Person()) } }

Error:

UncaughtExceptionError: Crashed due to an uncaught exception RealmTest crashed due to an uncaught exception `NSRangeException`. Reason: Cannot remove an observer <RealmSwift.SwiftUIKVO 0x60000370ed40> for the key path "name" from <RLM:Unmanaged Person 0x60000194ee80> because it is not registered as an observer.. ================================== | RemoteHumanReadableError: Failed to update preview. | | The preview process appears to have crashed. | | Error encountered when sending 'previewInstances' message to agent. | | ================================== | | | RemoteHumanReadableError: The operation couldn’t be completed. (BSServiceConnectionErrorDomain error 3.) | | | | BSServiceConnectionErrorDomain (3): | | ==BSErrorCodeDescription: OperationFailed
12 days later

Hi @Corey_de_la_Cruz, I just tested your view with that PR and the preview now works. If you want to try it for yourself (rather than waiting for it to be reviewed and released) then you can update SPM to use branch jf/fix-swiftui-invalidated-obj

Thanks for the update! I had to modify the source to get my project to run, and did notice it helped with the previews (didn’t realize it was the same issue).

I’ll use that branch for now, thanks!

Closed on Mar 22, 2021

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.