R – Cocoa Touch Question. Using KVO in a touch sequence context

cocoacocoa-touchkey-value-observingobjective cuikit

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

Best Answer

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.