您的位置:首页 > 其它

NSNotificationCenter观察者模式

2015-11-04 20:22 375 查看
NSNotificationCenter实现了观察者模式,允许应用的不同对象间以松耦合的方式进行通信。



NSNotificationCenter相当于一个消息中心,首先由Observer组件向NSNotificationCenter进行注册—表明该Observer组件对哪些NSNotification感兴趣。

当Poster向NSNotificationCenter发送NSNotification之后,所有在NSNotificationCenter上注册过的、对该NSNotification感兴趣的Observer对会被激发。

NSNotification代表Poster与Observer之间的信息载体,该对象包含如下只读属性。

@property (readonly, copy) NSString *name;
通知的名字

@property (nullable, readonly, retain) id object;
通知的Poster

@property (nullable, readonly, copy) NSDictionary *userInfo;
用于携带通知的附加信息

发送通知:

- (void)postNotification:(NSNotification *)notification;


- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;


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


注册通知:

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


- (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block


使用NSNotificationCenter除了可以监听系统组件发出的通知(系统已经命名好名称)之外,也可以监听程序自己发出的通知(通知名称由自己命名)。

监听系统组件发出的通知:

- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishLaunching) name:UIApplicationDidFinishLaunchingNotification object:[UIApplication sharedApplication]];
}

-(void)finishLaunching{
NSLog(@"finishLaunching");
}


监听自定义通知:

- (void)viewDidLoad {
[super viewDidLoad];

UIButton* poster=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
poster.backgroundColor=[UIColor redColor];
[self.view addSubview:poster];

[poster addTarget:self action:@selector(post) forControlEvents:UIControlEventTouchUpInside];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenClick:) name:@"click" object:nil];

}

-(void)post{
NSNotification* notication=[[NSNotification alloc] initWithName:@"click" object:nil userInfo:@{@"name":@"ricky"}];
[[NSNotificationCenter defaultCenter] postNotification:notication];
}

-(void)whenClick:(NSNotification*)notificaton{
NSLog(@"name=%@",[notificaton.userInfo objectForKey:@"name"]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: