I had a problem recently with Core Data transient properties, my own fault.

What I hoped they would be was full-fledged members of the database which just happened not to be saved to disk.

What they actually are is glorified instance variables. The trouble with using a custom subclass ivar is that its value is only present in the specific object you set it on. If you get a different object representing the same entity, say from another context, it won’t have that value. These can lead to lots of problems.

I wrote a sample Mac app, available on github, that demonstrates the problem. Here’s me setting the “name” property for a couple of entities:

Here’s me using the “Refresh” button to use a second managed object context to retrieve those same entities:

Names are gone! (And pointer values are different.) If I change the name attribute to not be transient, the names are preserved, even though the pointer values are still different:

I’m sliding over a lot of details here. This post by Jakob Stoklund Olesen has more information, but since it’s from 2007, it may be out of date. (It’s still the first google hit for “Core data transient properties”, however.)

2 thoughts on “Fleeting”

  1. Transient properties are specifically there to act as “glorified instance variables.” Their main use is as transient attributes whose type is undefined, which are (in turn) persisted as some other type. For some types of objects you can use transform able properties instead, but for something simple that has a direct NSString representation, it’s often more straightforward to use a (transient undefined, persistent string) representation or the like.

    For example, I have a personal app that has an entity one of whose attributes is a URL to a web page. I model that as a transient pageURL attribute whose type is undefined, and a persistent pageURLString attribute of string type. The corresponding class does the conversion itself in -willSave and -awakeFromFetch, and the rest of the app only uses pageURL, not pageURLString.

    And that’s the other advantage of transient properties: They’re not only glorified instance variables, they’re also still Core Data modeled properties, so you can do things like add information to their attribute description’s userInfo, discover them when traversing the model programmatically, undo and redo changes to them automatically via the object’s context’s undoManager, and so on.

Comments are closed.

%d bloggers like this: