2

In a view controller I create an array of subviews, which can be removed from the parent view at any time, so their lifespan is shorter than that of the view controller.

When creating them I do pretty much this:

  • Alloc/init the subview
  • add the view controller as an observer of the subview's frame property.
  • add it to a retained array
  • add it to the view
  • release it

The subview doesn't have a reference to the view controller.

When the user removes the subview, it gets deallocated, and I get a error in the console telling me the observer of the view's frame key path has not been removed.

How can I remove the observer when the subview being observed does not keep a reference to observer?

Isn't there anyway to do something like removeAllObservers?

I would prefer not to have to create a reference to the observer in the subview, as it somewhat defeats the point of KVO (I might as well use a delegate set up).

Jonathan.
  • 53,997
  • 54
  • 186
  • 290
  • 1
    Couldn't you remove the observer when you remove the UIView from the retained array? – Alex Deem Dec 08 '11 at 22:47
  • Could you tell the observer to also observe the subview itself, and stop its observation when the view closes? I'm not sure if this is possible - if not, see cwieland's answer. – Daniel Dec 09 '11 at 02:31
  • But then what happens if the view controller is deallocated before the subview? I know it would deallocate the subview, by releasing the array and removing the sub views, is it safe to try remove an observer that is already removed? – Jonathan. Dec 09 '11 at 07:41

1 Answers1

0

I am not sure why you are observing the frame but If you are just wanting to know when it gets deleted you could instead use NSNotificationCenter. From there your subview can post to the notification center that it's been changed/deleted. Your parent view will then see that notification and can do something with it depending on the what is in the notification. It is somewhat a more loosely bound kvo.

Here is a great example on setting it up. Send and receive messages through NSNotificationCenter in Objective-C?

In this way the superview just has to remove itself from watching that term in notification center when it gets release/unloaded.

In any case it is another way to approach it besides KVO and delegates.

Community
  • 1
  • 1
utahwithak
  • 6,235
  • 2
  • 40
  • 62
  • I dont want to observe when the frame changes so I could update the frames of other views. I'm already using the notification center for see when the view is deleted. – Jonathan. Dec 09 '11 at 07:37