Objective-C 通知
2016-01-27 20:07
609 查看
创建一个老师类 和 学生类 实现通知
/** * 老师类 * Teacher.h * */ #import <Foundation/Foundation.h> @interface Teacher : NSObject //这里设置成单例 以为只有一个老师发通知 + (Teacher *)sharedTeacher; //老师发通知 - (void)sendMessage; @end /** * Teacher.m */ #import "Teacher.h" static Teacher *t = nil; @implementation Teacher + (Teacher *)sharedTeacher { if (t == nil) { t = [[Teacher alloc] init]; } return t; } - (void)sendMessage { //注册通知 中心 [[NSNotificationCenter defaultCenter] //发通知 - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo; [[NSNotificationCenter defaultCenter] postNotificationName:@"mmff" object:self userInfo:@{@"notice":@"十月一日放假 7天"}]; } @end /** * 学生类 * Student.h */ #import <Foundation/Foundation.h> @interface Student : NSObject //接收通知 - (void) receiveMessage; @end /** * Student.h * */ #import "Student.h" @implementation Student - (void)receiveMessage { //注册通知中心 然后响应通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hoppy:) name:@"mmff" object:nil]; } //响应通知 - (void)hoppy:(NSNotification *)notice { NSDictionary *d = [notice userInfo]; NSLog(@"%@",[d objectForKey:@"notice"]); } //移除通知 - (void)dealloc { //移除某个通知 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"mmff" object:nil]; //移除所有通知 //[[NSNotificationCenter defaultCenter] removeObserver:self]; } @end /** * Student.h * */ #import "Student.h" @implementation Student - (void)receiveMessage { //注册通知中心 然后响应通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hoppy:) name:@"mmff" object:nil]; } //响应通知 - (void)hoppy:(NSNotification *)notice { NSDictionary *d = [notice userInfo]; NSLog(@"%@",[d objectForKey:@"notice"]); } //移除通知 - (void)dealloc { //移除某个通知 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"mmff" object:nil]; //移除所有通知 //[[NSNotificationCenter defaultCenter] removeObserver:self]; } @end
相关文章推荐
- Error: while loading shared libraries: libXXX.so.X: cannot open shared object file: No such file
- Objective-C 单例
- JSON对象中的JSONObject和JSONArray以及与Map、String、数组的转化
- Objective-C特性:Runtime
- org.hibernate.NonUniqueObjectException: a different object with the same identifier value was ...
- python object类
- 对 removeObject 的理解
- node之object-assign
- Android小问题:String转换Json,以及org.json.JSONObject与org.json.JSONArray相互添加
- JSONObject 类
- Could not find MessageBodyWriter for response object of type: application/json
- 理解 Objective-C Runtime
- iOS开发系列—Objective-C之Foundation框架
- MockObject
- JavaScript values and Objective-C objects
- Objective-C中的instancetype和id关键字
- object_id()说明
- Java7中如何将Object对象转化为int对象
- Android开发将List转化为JsonArray和JsonObject
- iOS开发笔记--Objective-C实现多继承