删除自身作为观察者时崩溃 - CALayer
当我在 -(void)dealloc 中删除自己作为观察者时,我的 CALayer 子类发生崩溃:
- (void)dealloc {
[[NSUserDefaults standardUserDefaults] removeObserver:self forKeyPath:@"showColorLabels"];
[colorLabel release];
[_color release];
[super dealloc];
}
抛出异常。它说 self 尚未被添加为观察者。这只发生在特定情况下,在调用 [CATransactionlush] 之后。
我使用 Instruments 来查看对象何时被分配。它说它是通过调用 CALayerGetPresentationLayer() 分配的。我不确定这是如何工作的,但我猜这是我原始层的副本,所以 init 从未被调用,我也从未被添加为观察者。
在删除自己之前,我如何检查我是否是观察者,或者如何判断我是否是表示层?
布里杰·麦克斯韦
I am having a crash in my CALayer subclass when I remove myself as an observer in -(void)dealloc:
- (void)dealloc {
[[NSUserDefaults standardUserDefaults] removeObserver:self forKeyPath:@"showColorLabels"];
[colorLabel release];
[_color release];
[super dealloc];
}
An exception is thrown. It says that self has not been added as an observer. This only happens in a certain case, after [CATransaction flush] is called.
I used Instruments to see when the object was allocated. It says it was allocated with the call CALayerGetPresentationLayer(). I am not sure how this works, but I guess this is a copy of my original layer, so init was never called, and I was never added as an observer.
How can I either check that I am an observer before removing myself, or maybe tell if I am a presentation layer?
Bridger Maxwell
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在这里找到了一个很好的解决方案: https://stackoverflow.com/a/6714561/958017
你可以使用尝试-调用removeobserver中的catch块:
I found a good solution here: https://stackoverflow.com/a/6714561/958017
you can use a try-catch block in your call to removeobserver:
好吧......问一个明显的问题作为回应:
你在哪里添加
self
作为@"showColorLabels
键的观察者?你不必调用
-removeObserver:forKeyPath:
除非您首先明确地将对象添加为观察者。Welllll.... to ask the obvious question in response:
Where are you adding
self
as an observer of the@"showColorLabels
key?You shouldn't have to invoke
-removeObserver:forKeyPath:
unless you explicitly added the object as an observer in the first place.