本文介绍了避免保留周期,NSNotificationCenter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种分类方法是否可以避免在NSNotificationCenter观察者上进行额外保留?

Will this category method allow me to avoid additional retains on NSNotificationCenter observers?

#import "NSNotificationCenter+Util.h"

@implementation NSNotificationCenter (Util)

- (void)addWeakObserver:(nonnull NSObject*)observer selector:(nonnull SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject {
    __weak NSObject *weakObserver = observer;
    [self addObserver:weakObserver selector:aSelector name:aName object:anObject];
}

@end

目标是使对象死亡而不必将其删除.

The goal is to have the object die without having to remove it.

注意:我正试图避免这种情况导致保留周期:

Note: I'm trying to avoid this causing retain cycles:

推荐答案

否— weakObserver将是weak,因此,如果observer被释放,则nil将自动nil,但是如果addObserver:...保留观察者,则它保留了观察者.对象中没有关于以前引用对其保存方式的历史记录,而是引用本身控制着自己的行为.

No — weakObserver will be weak, so will automatically nil if observer is deallocated, but if addObserver:... retains the observer then it retains the observer. There's no history in an object as to the ways that previous references have held it, it's the references themselves that control their own behaviour.

但是,NSNotificationCenter不保留其观察者,并且观察者几乎从不保留通知中心.没有保留周期.您所引用的文本或多或少地说明了这一点:通知中心中存储的指针将变得悬而未决,即未声明所有权.

However, NSNotificationCenter doesn't retain its observers, and observers almost never retain the notification centre. There is no retain cycle. The text you've quoted more or less says this: that pointers stored within the notification centre will become dangling, i.e. it is not asserting ownership.

您所做的操作也不会自动将引用存储在中心内.nil.

What you've done also won't make the references stored within the centre automatically nil.

从iOS 9和OS X v10.11开始,此行为已修复.通知中心将弱引用用于所有可以弱引用的对象.

As of iOS 9 and OS X v10.11, this behaviour is already fixed. A weak reference is used by the notification centre for all objects that can be referenced weakly.

这篇关于避免保留周期,NSNotificationCenter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:14