Realm-cocoa: Edit object properties outside write transaction (as a regular object)

Created on 29 Aug 2016  路  3Comments  路  Source: realm/realm-cocoa

Goals

Being able to edit object properties outside a write transaction. As I could with a regular object.

Expected Results

Successfully update object properties

Actual Results

failed: caught "RLMException", "Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.

Steps to Reproduce

  1. Retrieve an object from Realm
  2. Modify its properties outside the write transaction

    Code Sample

My database test case:

it("update an existing usage") {
  try! self.database.add(self.slug)

  let expectedUsage = try! self.database.retrieveUsage(self.slug) // try realm.write { real.objects(...) return myObject }
  expectedUsage.incrementTracesToUpload() // TODO: Must be in write transaction..
  expectedUsage.setTracesUploaded()

  try! self.database.update(expectedUsage) // try realm.write { realm.add(myObject, update: true) }

  let retrievedStatistics = try! self.database.retrieveUsage(self.slug)
  expect(retrievedStatistics).to(equal(expectedUsage))
}

I _do understand_ that I should put my code in a write completion block but I don't want to give the possibility to my final user to directly access Realm and call whatever he wants (using myObject.realm?) ?
I just want to give away a simple object once retrieve from Realm. I don't want Realm to update my object everytime I change it.

Is there any way to do so without having to encapsulate my Object into an other or maybe create a copy ?

Maybe my approach is bad, I'm open to any suggestion.

Version of Realm and Tooling

Realm version: 1.0.2
Xcode version: 7.3
iOS/OSX version: 9.3
Dependency manager + version: CocoaPods 1.1.0.beta.1

T-Help

Most helpful comment

You can already make an unmanaged shallow copy of an object by using Object.init(value:) passing in the managed instance of the object. We don't yet support recursively copying object properties to make a deep copy using this method, but we're tracking that feature request here, and there's a few workarounds. If this doesn't cover what you're looking for, feel free to reopen this issue with an explanation.

All 3 comments

It sounds like you want an unmanaged copy. Is this correct?

This is exactly what I'm hoping for !
I'm working on a SDK and I don't want to share objects with Realm accessible from them.

You can already make an unmanaged shallow copy of an object by using Object.init(value:) passing in the managed instance of the object. We don't yet support recursively copying object properties to make a deep copy using this method, but we're tracking that feature request here, and there's a few workarounds. If this doesn't cover what you're looking for, feel free to reopen this issue with an explanation.

Was this page helpful?
0 / 5 - 0 ratings