SwiftUI previews with ObservedRealmObject

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)

Previews should work. Do you have any sample code? What’s the preview error?

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

Hi @Jason_Flax – I’m seeing the same exception when I test this view (using Realm Cocoa 10.7.0)

There is a pull request open to fix this: Add guard to KVO subscription to prevent multiple observer removals to occur unnecessarily by jsflax · Pull Request #7132 · realm/realm-swift · GitHub.

2 Likes

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!

1 Like

@Corey_de_la_Cruz glad to hear that it’s working. To state the obvious, you can watch the PR to know when it gets merged.

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