Transient Properties of the Realm

We have been exploring Realm as an alternative data store for some of our iOS projects. All in all, it has been a very positive experience. Creating models, inserting data, and querying it back out again is much simpler then some of the other options on the platform (CoreData, etc…)

When one of our developers tried to start storing an image on a model we had to teach our model how to deal with a UIImage object. Our initial model looked like this when written in Swift language=”swift”>class MyTable: RLMObject {
dynamic var imageData: NSData = NSData()
dynamic var imagePresent: Bool = false
var image: UIImage? {
get: { … }
set(newImage): { … }
}
}
</code>

</pre>
The current version of Realm tries to persist all properties of an RLMObject, not just the dynamic ones. That means the computed property image caused a runtime error in our project like this:

*** Terminating app due to uncaught exception 'RLMException',
reason: '(null)' is not supported as an RLMObject property. 
All properties must be primitives, NSString, NSDate, NSData, RLMArray, or subclasses of RLMObject. 
See http://realm.io/docs/cocoa/api/Classes/RLMObject.html for more information.

Since we don’t want our computed property to be stored in the database anyway, the solution is to override the ignoreProperties class method.

class MyTable: RLMObject {
  dynamic var imageData: NSData = NSData()
  dynamic var imagePresent: Bool = false
  var image: UIImage? {
    get: { … }
    set(newImage): { …  }
  }
  override class func ignoredProperties() -> [AnyObject]! {
    return ["image"]
  }
}
Photo of Tim Bugai

Programming since the age of 8, Tim has a strong background in agile software development, Ruby, JavaScript, and iOS. He’s also helping our team with mobile application development, often leading the charge.

Comments

  1. mazyod@gmail.com
    Maz
    February 23, 2015 at 16:23 PM

    Holy crap, it’s actually mentioned in their docs, right after a code block.. Totally missed it. Thanks for the write up.
    http://realm.io/docs/cocoa/0.90.6/#customizing-models

  2. daniel.saidi@gmail.com
    Daniel
    January 13, 2016 at 14:36 PM

    Hi, thanks for this write-up. Have you experiences any problems with this in Realm lately. I use Realm 0.97.0 and it crashes due to my calculated image properties, even though I have them registered as excluded properties.

  3. thanos17997@gmail.com
    john
    January 28, 2019 at 15:58 PM

    nice post