博客
关于我
Objective - C 小谈:消息机制的原理与使用
阅读量:794 次
发布时间:2023-02-17

本文共 2267 字,大约阅读时间需要 7 分钟。

NotificationCenter及其在iOS开发中的应用

1. 通知中心(NSNotificationCenter)

每一个iOS应用程序都有一个专门的通知中心(NSNotificationCenter)实例,负责协助不同对象之间的消息通信。这个机制符合观察者模式(Observer Pattern),允许任何对象向通知中心发布通知(NSNotification),而其他感兴趣的对象(观察者)可以在特定通知发布时接收到此通知。

2. 通知(NSNotification)

一个通知通常包含以下三个属性:

  • name:通知的名称( NSString *)
  • object:发布通知的对象( id)
  • userInfo:额外的用户信息( NSDictionary *)

通过以下方法可以初始化一个通知:

+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo;

3. 发布通知

通知中心提供了多种方法来发布通知:

- (void)postNotification:(NSNotification *)notification;- (void)postNotificationName:(NSString *)aName object:(id)anObject;- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

4. 注册通知监听器

通知中心允许注册通知监听器(Observer),通过以下方法可以实现:

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block;

5. 取消注册通知监听器

在取消注册监听器前,需确保已从通知中心移除注册:

- (void)removeObserver:(id)observer;- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;

通常在监听器的析除阶段(如 dealloc 方法)取消注册:

- (void)dealloc {    [[NSNotificationCenter defaultCenter] removeObserver:self];}

6. 通知与代理的比较

共同点

  • 都能实现对象间的通信。
  • 例如,A对象通知D对象某个事件发生,并传递数据。

不同点

  • 代理:一对一关系(只能通知特定对象)。
  • 通知:多对多关系(一个对象可以通知多个对象,一个对象也可以接收多个通知)。

7. 通知对象的常见用法

7.1 UIDevice 通知

通过 UIDevice 类获取设备信息:

+ (UIDevice *)currentDevice;

常见通知名称:

  • UIDeviceOrientationDidChangeNotification
  • UIDeviceBatteryStateDidChangeNotification
  • UIDeviceBatteryLevelDidChangeNotification
  • UIDeviceProximityStateDidChangeNotification

7.2 键盘通知

键盘状态改变时,系统会发布以下通知:

  • UIKeyboardWillShowNotification
  • UIKeyboardDidShowNotification
  • UIKeyboardWillHideNotification
  • UIKeyboardDidHideNotification
  • UIKeyboardWillChangeFrameNotification
  • UIKeyboardDidChangeFrameNotification

附加信息(字典)包括:

  • UIKeyboardFrameBeginUserInfoKey
  • UIKeyboardFrameEndUserInfoKey
  • UIKeyboardAnimationDurationUserInfoKey
  • UIKeyboardAnimationCurveUserInfoKey

8. 总结

NotificationCenter 是iOS开发中的重要工具,通过发布通知和注册监听器,实现多对象间的高效通信。理解其原理和应用,对于开发实践至关重要。

转载地址:http://mynfk.baihongyu.com/

你可能感兴趣的文章
Npp删除选中行的Macro录制方式
查看>>
NR,NF,FNR
查看>>
nrf24l01+arduino
查看>>
nrf开发笔记一开发软件
查看>>
nrm —— 快速切换 NPM 源 (附带测速功能)
查看>>
nrm报错 [ERR_INVALID_ARG_TYPE]
查看>>
NS3 IP首部校验和
查看>>
NSDateFormatter的替代方法
查看>>
NSError 的使用方法
查看>>
NSGA-Ⅲ源代码
查看>>
nsis 安装脚本示例(转)
查看>>
NSJSON的用法(oc系统自带的解析方法)
查看>>
nslookup 的基本知识与命令详解
查看>>
NSOperation基本操作
查看>>
NSRange 范围
查看>>
NSSet集合 无序的 不能重复的
查看>>
NSURLSession下载和断点续传
查看>>
NSUserdefault读书笔记
查看>>
NS图绘制工具推荐
查看>>
NT AUTHORITY\NETWORK SERVICE 权限问题
查看>>