删除自身作为观察者时崩溃 - CALayer

发布于 2024-08-22 19:41:50 字数 515 浏览 6 评论 0原文

当我在 -(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ま柒月 2024-08-29 19:41:50

我在这里找到了一个很好的解决方案: https://stackoverflow.com/a/6714561/958017

你可以使用尝试-调用removeobserver中的catch块:

@try{
   [[NSUserDefaults standardUserDefaults] removeObserver:self forKeyPath:@"showColorLabels"];
}@catch(id anException){
   //Whatever you want to do.
}

I found a good solution here: https://stackoverflow.com/a/6714561/958017

you can use a try-catch block in your call to removeobserver:

@try{
   [[NSUserDefaults standardUserDefaults] removeObserver:self forKeyPath:@"showColorLabels"];
}@catch(id anException){
   //Whatever you want to do.
}
天气好吗我好吗 2024-08-29 19:41:50

好吧......问一个明显的问题作为回应:

你在哪里添加 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文