在视图控制器中,我创建了一个子视图数组,这些子视图可以随时从父视图中删除,因此它们的生命周期比视图控制器短。
创建它们时,我几乎这样做:
- Alloc/init 子视图
- 添加视图控制器作为子视图的
frame
属性的观察者。
- 将其添加到保留数组中
- 将其添加到视图中
- 释放它
子视图没有对视图控制器的引用。
当用户删除子视图时,它会被释放,并且我在控制台中收到一条错误,告诉我视图的 frame
键路径的观察者尚未删除。
当被观察的子视图不保留对观察者的引用时,如何删除观察者?
无论如何,没有办法做类似 removeAllObservers
的事情吗?
我不想在子视图中创建对观察者的引用,因为它在某种程度上违背了 KVO 的要点(我不妨使用委托设置)。
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).
发布评论
评论(1)
我不确定您为什么要观察该框架,但如果您只是想知道它何时被删除,您可以使用 NSNotificationCenter。从那里您的子视图可以将其已更改/删除的信息发布到通知中心。然后,您的父视图将看到该通知,并可以根据通知中的内容对其执行某些操作。它在某种程度上是一个更松散绑定的 kvo。
这是一个很好的设置示例。
在 Objective-C 中通过 NSNotificationCenter 发送和接收消息?
这样,当超级视图被释放/卸载时,它只需将自己从通知中心的该术语中删除即可。
无论如何,这是除了 KVO 和代表之外的另一种处理方式。
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.