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

Add a Comment

Hmm...that didn't work.

Something went wrong while adding your comment. If you don't mind, please try submitting it again.

Comment Added!

Your comment has been added to this post. Please refresh this page to view it.

Optional. If added, we will display a link to the website in your comment.
Optional. Never shared or displayed in your comment.
  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