NSNotificationCenter研究小记

1.NSNotificationCenter对observer的引用是弱引用,即引用计数不会增加。

2.在iOS 9之前,这个引用类似于unsafe_unretained,observer对象被销毁后不会被置为nil,因此接收到通知时会导致野指针而崩溃。

3.在iOS 9以上,这个引用类似于weak,即使没有执行removeObserver方法,在observer对象被销毁后接收通知不会引发野指针崩溃。

4.UIViewController对象会在dealloc时执行removeObserver方法(未确认是否跟iOS版本有关)。

5.UIView对象在dealloc时不会执行removeObserver方法,目前已知会执行removeObserver方法的仅有UIViewController。

6.iOS官方文档关于addObserver:selector:name:object:这个方法的描述中说明了“如果你的App的运行在iOS 9.0或更新版本上则不需要手动移除通过该方法添加的观察者(Observer)对象”,详情请看官方文档的Discussion部分。

官方文档

addObserver:selector:name:object:

Adds an entry to the notification center’s dispatch table with an observer and a notification selector, and an optional notification name and sender.


Declaration

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSNotificationName)aName object:(id)anObject;

Parameters

observer
Object registering as an observer.


aSelector
Selector that specifies the message the receiver sends observer to notify it of the notification posting. The method specified by aSelector must have one and only one argument (an instance of NSNotification).


aName
The name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.


anObject
The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.

Discussion

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don’t need to unregister an observer in its dealloc method. Otherwise, you should call removeObserver:name:object: before observer or any object passed to this method is deallocated.

此处翻译一下:
如果你的App运行在 iOS 9.0 以上或 macOS 10.11 以上,那么你可以不用再观察者对象的dealloc方法中将其移除(即调用removeObserver方法)。否则,你需要在观察者对象(或任意被传入到该方法中的对象)被销毁时调用removeObserver:name:object:方法将其移除。

参考:
iOS NSNotificationCenter 使用姿势详解 – 简书
NSNotificationCenter和NSNotificationQueue学习笔记 – 简书

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇