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"]
}
}
Comments
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
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.
nice post