卸下观察者 [英] Removing an Observer

查看:92
本文介绍了卸下观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在NSManagedObject子类中,我有代码…

In a NSManagedObject Sub Class I have the code …

- (void) awakeFromInsert { 
[self addObserver:[NSApp delegate] forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil]; 
}

将我的App Delegate添加为观察者,我现在要做的是从我的应用程序代表内部,我想将自己删除为NSManagedObject子类的观察者。

Which adds my App Delegate as an Observer, what I want to do now is from inside my App Delegate, I want to remove itself as an Observer for my NSManagedObject Sub Class.

我该怎么做?
谢谢。

How would I do this? Thanks.

我正在考虑将其添加到我的应用程序委托中

I was thinking of adding this to my App Delegate

[JGManagedObject removeObserver:self forKeyPath:@"name"];

但不幸的是 removeObserver:forKeyPath:不是一个类方法。

but unfortunately removeObserver:forKeyPath: is not a Class Method.

推荐答案

对于这种情况,最好重新考虑设计。为此,委托人必须对托管对象本身具有一些特定的知识才能做到这一点-并且委托人必须对生命周期中何时应该(或希望)停止观察有一些了解。

For something like this, it's probably best to rethink the design. The delegate, in this case, would have to have some specific knowledge of the managed object itself in order to do this -- and the delegate would have to have some idea about when in the lifecycle it should (or would want to) stop observing the object.

您有几种选择。您可以让委托在创建它时开始观察它,而在放弃所有权时停止观察它,而不是从插入状态中唤醒。如果这在您的设计中不可行,则可以让该对象在释放时移除其观察者。如果这是一劳永逸的操作(基本上,委托只关心一次),则可以在第一个更改通知之后删除观察者。但是,由于您是在该对象的创建生命周期内创建观察值的,因此最好在销毁该对象时删除该观察值:

You have a few choices. Instead of doing this in awake from insert, you could have the delegate start observing it when it creates it and then stop observing it when it gives up ownership. If that is not feasible in your design, you could have the object remove its observer when it is deallocated. If this is a fire-and-forget (basically the delegate only cares once), you could remove the observer after the first change notification. Since, however, you created the observation within the creation lifecycle of this object, it is probably best to remove that observation at the destruction of the object:

- (void)dealloc
{
  [self removeObserver:[NSApp delegate] forKeyPath:@"name"];
  // other clean-up
  [super dealloc];
}

当对象从获取和故障中唤醒时,您可能还想这样做并在对象将成为故障时释放观察者。

You might also want to do this when the object awakes from fetch and from fault and release the observer when the object will become a fault.

这篇关于卸下观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆