Key value observing NSManagedObjects

  • Hi,

    I'd like to key-value observe a property of an NSManagedObject. I
    tried to register an observer (in the init: method of my app's
    controller) using "addObserver:forKeyPath:options:" but it doesn't
    work because the observation is lost as my object gets dealloc'ed soon
    after I register as an observer. This is specified in the Core Data
    documentation : "Core Data "owns" the life-cycle of managed objects.
    [...] managed objects can be instantiated, destroyed, and resurrected
    by the framework as it requires."

    So how can I observe a Core Data object property and how can the
    observation survive the multiple instantiations/desctructions of the
    NSManagedObject?

    Thanks,
    -Martin.
  • > I'd like to key-value observe a property of an NSManagedObject. I
    > tried to register an observer (in the init: method of my app's
    > controller) using "addObserver:forKeyPath:options:" but it doesn't
    > work because the observation is lost as my object gets dealloc'ed soon
    > after I register as an observer.

    If you want the object to last, why don't you -retain it ?
    Typically, if the object is in a collection managed by an array
    controller, the controller does this.

    > This is specified in the Core Data
    > documentation : "Core Data "owns" the life-cycle of managed objects.
    > [...] managed objects can be instantiated, destroyed, and resurrected
    > by the framework as it requires."

    This is true, but managed objects still conform to the API
    requirements of NSObject.  If you call -retain on it, it's not going
    away.  If you use retain/autorelease, it'll be in the autorelease
    pool just like any other object.

    This piece of the documentation is intended to dispel assumptions
    about what happens after the retain count hits 0, or if any object is
    fetched repeatedly, or the existence or destruction of managed
    objects you did not explicitly fetch.

    For thread safety and performance, the framework reserves the right
    to behave strangely when you're not looking.  For example, -dealloc
    might be called asynchronously following the last call to -release.
    There's nothing in the API of NSObject that states -dealloc must be
    called immediately from within -release, but a lot of developers
    assume that since most objects work that way.
    --

    -Ben