views:

191

answers:

1

I would like to use KVO in the following context:

1) In touchesBegan:withEvent: I alloc/init an instance of an object that I then observe via KVO

My intent is to observe varous behaviors of the object throughout its life time.

2) In touchesEnded:withEvent: I assign this instance to an NSMutableArray and release the instance reference since NSMutableArray now retains it. I also must remove the oberver of the instance via removeObserver:forKeyPath:

This is problematic because I now have lost all observation unless I add the observe back again to the array element which smells bad.

Is there a way to have the observer remain attached to the object regardless of who owns it?

Thanks, Doug

+1  A: 

In Objective-C, you don't "own" an object, you merely have a claim on it. You don't need to release the instance just because the NSMutableArray retains it -- you can both have a claim on it. When you've finished with the object, remove yourself as an observer and release the object. When you've finished with the NSMutableArray, release that. This way, everything takes care of itself.

hatfinch
Some context. Each time touchesBegan:withEvent: is called a member of the parent object allocs an instance, briefly, and then hands it off to the NSMutableArray. Over and over. Once the object is handed to the array the instance nolonger needs it and thus should release it. Not releasing the member's claim to the object would constitute a memory leak as I would then not be balancing each alloc/init with a corresponding release.I need the freedom to bind the observer to the instanced object. Right now KVO only appears to know about references to instances, not the instance itself.
dugla
Ah, so you're just using the array as a way to store an indeterminate number of objects, but you want your original view (the array owner) to continue to be notified of all changes to the observed property of all of those objects?In that case, don't remove the observer when you add the object to the mutable array, but make sure that immediately prior to releasing the mutable array you iterate over its members removing the observer at that point.
hatfinch
Oh, and I just noticed you say above that the array shrinks over time, so you'll need to remove the observer each time you remove an object from the array. You might even want to create a wrapper class for your array which handles the adding and removing of observers automatically when you add and remove objects, and removes them all in dealloc prior to calling super.
hatfinch