IOS 消息机制(NSNotificationCenter)
IOS 消息机制(NSNotificationCenter)
1. 观察者注册消息通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserProfileSuccess:) name:@"Notification_GetUserProfileSuccess" object:nil];
notificationObserver 观察者 : self
notificationSelector 处理消息的方法名: getUserProfileSuccess
notificationName 消息通知的名字: Notification_GetUserProfileSuccess
notificationSender 消息发送者 : 表示接收哪个发送者的通知,如果第四个参数为nil,接收所有发送者的通知
2. 发送消息通知
//UserProfile Is A Model
//@interface UserProfile : NSObject
[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_GetUserProfileSuccess" object:userProfile userInfo:nil];
notificationName 消息通知的名字: Notification_GetUserProfileSuccess
notificationSender 消息发送者: userProfile
3. 观察者处理消息
- (void) getUserProfileSuccess: (NSNotification*) aNotification { self.userProfile = [aNotification object]; lblName.text = self.userProfile.Name; lblEENO.text = self.userProfile.EENO; lblNric.text = self.userProfile.NRIC; lblBirthday.text =self.userProfile.Birthday; lblHireDate.text = self.userProfile.Hiredate; txtMobilePhone.text = self.userProfile.Mobile; txtEmail.text = self.userProfile.Email; }
NSNotification 接受到的消息信息,主要含:
Name: 消息名称 Notification_GetUserProfileSuccess
object: 消息发送者 userProfile
userInfo: 消息传递的数据信息
4. 观察者注销,移除消息观察者
虽然在 IOS 用上 ARC 后,不显示移除 NSNotification Observer 也不会出错,但是这是一个很不好的习惯,不利于性能和内存。
注销观察者有2个方法:
a. 最优的方法,在 UIViewController.m 中:
-(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }
If you see the method you don't need to call [super dealloc]; here, only the method without super dealloc needed.
b. 单个移除:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess" object:nil];
相关文章
- 如何在Ubuntu 13.04和13.10上安装iOS 7的图标
- How to change in the Cocos2d-x project from landscape to portrait both in iOS and Android
- 【AGC】如何在iOS上集成华为AGC应用内消息
- 《iOS组件与框架——iOS SDK高级特性剖析》——第2章,第2.1节示例应用
- iOS日常工作之常用宏定义大全
- iOS开发基础:OC数组对象NSArray的常用方法
- iOS - 设置导航栏之标题栏居中、标题栏的背景颜色
- iOS系统消息
- 关于iOS多线程,你看我就够了
- SwiftUI iOS 16.4 中的新功能 iOS 16.4 在 SwiftUI 中引入的消息快速浏览
- iOS 10 消息推送(UserNotifications)秘籍总结(一)
- IOS 基于APNS消息推送原理与实现(JAVA后台)
- iOS开发系列--通知与消息机制
- 《腾讯iOS测试实践》一一1.8 小结
- 小知识随手记(八):颜色转换、const常量的改动内因、js消息队列、JSON.stringify()的一些特性、多背景图写法、懒加载原理、document.body与document.documentElement区别及使用、移动ios卡顿问题、移位运算符、nextSibling 和nextElementSibling的区别
- iOS 惊现大漏洞:无需密码即可访问你的 iPhone 照片或消息
- [置顶] Objective-C ,ios,iphone开发基础:protocol 协议(委托,代理)的声明
- iOS开发-聊天气泡的绘制和聊天消息列表
- 绕过密码就能访问iPhone照片或消息 连iOS 10也受影响