title: Realm Swift : Update an object inside a closure
body: <p>For the sake of the question, here's a simple example (with a few shortcuts) :</p>
  
  <pre><code>class Foo: Object {
    dynamic var id: Int = 0
    [...]
  }
  
  class Bar: Object {
    dynamic var id: Int = 0
    dynamic var foo: Foo?
  
    convenience required init(data: AnyObject) {
      self.init()
      self.id = data.id as! Int
  
      if let foo_id = data.foo_id as? Int {
        // Function querying the remote database and returning an object
        Foo.get(foo_id) { (foo) -&gt; Void in
          self.foo = foo // Foo object assigned, as expected
        }
      }
    }
  }
  </code></pre>
  
  <p>If i'm doing the <code>self.foo = foo</code> in the closure of the <code>get()</code> function, i got an exception :</p>
  
  <blockquote>
    <p>exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'</p>
  </blockquote>
  
  <p>So if i'm adding a realm.write around it, as asked by the previous exception :</p>
  
  <pre><code>...
  Foo.get(foo_id) { (foo) -&gt; Void in
    let realm = Realm(path: Realm.defaultPath)
    realm.write {
      self.foo = foo
    }
  }  
  ...
  </code></pre>
  
  <p>This time I get a new one :</p>
  
  <blockquote>
    <p>exception 'RLMException', reason: 'Can not add objects from a different Realm'</p>
  </blockquote>
  
  <p>I'm stuck and i can't figure out what Realm is wanting from me here, the doc isn't helping.</p>
  
  <p>I'm not that used to Realm, so i suppose I got something wrong on how it works, but i don't know what.</p>
  
  <p>Thanks for your help</p>