[英]How to remove KVO observer?
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: 创建它们时,我几乎这样做:
frame
property. frame
属性的观察者。 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. 当用户删除子视图时,它会被释放,并且控制台中出现一个错误,告诉我该视图的
frame
关键路径的观察者尚未被删除。
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
? 反正没有做诸如
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). 我宁愿不必在子视图中创建对观察者的引用,因为它有点违反了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. 我不确定为什么要观察框架,但是如果您只是想知道何时删除框架,可以改用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.
它有点松散地绑定了kvo。
Here is a great example on setting it up. 这是一个很好的设置示例。 Send and receive messages through NSNotificationCenter in Objective-C?
通过Objective-C中的NSNotificationCenter发送和接收消息?
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. 无论如何,这是除KVO和代表之外的另一种处理方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.