gpt4 book ai didi

cocoa-touch - 为什么我需要在我正在观察的对象被释放之前删除一个通知观察者?

转载 作者:行者123 更新时间:2023-12-04 02:55:51 28 4
gpt4 key购买 nike

来自 https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html :

You must invoke removeObserver: or removeObserver:name:object: before any object specified by addObserverForName:object:queue:usingBlock: is deallocated

为什么在我正在观察其通知的对象被释放之前停止观察很重要?我理解为什么作为观察者的需要停止观察如果要消失并且 block 取决于我的存在,但我不明白为什么生命周期观察到的对象很重要。我是不是误解了这个?

最佳答案

I understand why I as the observer need to stop observing if I'm going to disappear and the block depends on my existence, but I don't understand why the lifetime of the observed object matters.

我认为可能的解释如下。

addObserverForName:object:queue:usingBlock 描述说:

Adds an entry to the receiver’s dispatch table with a notification queue and a block to add to the queue, and optional criteria: notification name and sender.

“发件人”在此上下文中只是 object 参数的另一个名称,它在以下术语中进行了描述:

The object whose notifications you want to add the block to the operation queue. If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to add the block to the operation queue.

因此,object 充当一种过滤器:当收到通知时,通知中心根据该值(如果存在)决定是否必须将 block 添加到指定的操作队列。

现在,考虑一下:

  1. 被观察对象被释放,观察者没有被移除;

  2. 创建了一个不同的对象,也能够发布通知,并且碰巧它与在点 1 处释放的对象具有相同的地址;

  3. 现在观察者将对第二个对象发布的通知使用react。

我承认这是一种非常罕见的情况,但它可能会发生,所以你最好针对它编写代码。

关于cocoa-touch - 为什么我需要在我正在观察的对象被释放之前删除一个通知观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14170661/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com