标签:
// 初始化通知中心 NSNotificationCenter *center =[NSNotificationCenter defaultCenter];
通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(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;
通知中心(NSNotificationCenter)提供了相应的方法来帮助发布通知
- (void)removeObserver:(id)observer; - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
- (void)dealloc { //[super dealloc]; 非ARC中需要调用此句 [[NSNotificationCenter defaultCenter] removeObserver:self]; }
两个新闻机构(腾讯新闻、新浪新闻),每当发布新闻时,通知订阅了该新闻的用户。
新闻机构类 NewsCompany.h
// 新闻发布机构 #import <Foundation/Foundation.h> @interface NewsCompany : NSObject /** * 机构名称 */ @property (nonatomic, copy) NSString *name; @end
NewsCompany.m
#import "NewsCompany.h" @implementation NewsCompany @end
订阅者类
Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject /** * 姓名 */ @property (nonatomic, copy) NSString *name; - (void)newsCome:(NSNotification *)note; @end
Person.m
#import "Person.h" #import "NewsCompany.h" @implementation Person // 收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入 - (void)newsCome:(NSNotification *)note { // 通知的发布者 NewsCompany *obj = note.object; NSLog(@"%@接收到了%@发出的通知,通知内容是:%@", self.name, obj.name, note.userInfo); } // 一般在监听器销毁之前取消注册 - (void)dealloc { // [super dealloc]; [[NSNotificationCenter defaultCenter] removeObserver:self]; } @end
通知中心
main.m
#import <Foundation/Foundation.h> #import "Person.h" #import "NewsCompany.h" int main(int argc, const char * argv[]) { @autoreleasepool { // 1.初始化机构 NewsCompany *tx = [[NewsCompany alloc] init]; tx.name = @"腾讯新闻"; NewsCompany *sina = [[NewsCompany alloc] init]; sina.name = @"新浪新闻"; // 2.初始化2个人 Person *zhangsan = [[Person alloc] init]; zhangsan.name = @"张三"; Person *lisi = [[Person alloc] init]; lisi.name = @"李四"; // 初始化通知中心 NSNotificationCenter *center =[NSNotificationCenter defaultCenter]; // 3.注册通知监听器 // zhangsan只监听tx发出的junshi_news_come通知 [center addObserver:zhangsan selector:@selector(newsCome:) name:@"junshi_news_come" object:nil]; // lisi监听tx发的所有通知 [center addObserver:lisi selector:@selector(newsCome:) name:nil object:tx]; // 4.发布通知 // tx发布了一则叫做junshi_news_come的通知 [center postNotificationName:@"junshi_news_come" object:tx userInfo:@{@"title" : @"伊拉克战争停止了", @"intro" : @"伊拉克战争停止了.........."}]; // sina发布了一则叫做junshi_news_come的通知 [center postNotificationName:@"yule_news_come" object:sina userInfo:@{@"title" : @"6456456456456", @"intro" : @"7657567567567"}]; } return 0; }
运行结果:
iOS 设计模式-NSNotificationCenter 通知中心
标签:
原文地址:http://www.cnblogs.com/jys509/p/4821253.html