IOS之通知

来源:互联网 发布:手机连接投影仪软件 编辑:程序博客网 时间:2024/05/22 03:15

通知是一种发送给一个或者多个观察者,用来通知其在程序中发生了某一个事件的消息。Cocoa中得通知机制遵循的是一种广播的模式。他是一种程序中事件的发起者或者处理者和其他想要知道该事件的对象沟通的一种方式。

通知机制的核心就是一个进程中单一实例的对象,被叫做通知中心(NSNotificationCenter)。当一个对象发布一个通知时,通知会被先发送到通知中心。通知中心的作用相当于是交流所.

#import <Foundation/Foundation.h>@interface King : NSObject-(void)sendMessage;@end

#import "King.h"@implementation King-(void)sendMessage{    NSNotification *notification = nil;    notification = [NSNotification notificationWithName:@"message" object:self userInfo:[NSDictionary dictionaryWithObject:@"king" forKey:@"name"]];    [[NSNotificationCenter defaultCenter] postNotification:notification];}@end

#import <Foundation/Foundation.h>@interface Worker : NSObject-(void)say:(NSNotification *)notification;@end

#import "Worker.h"@implementation Worker-(id)init{    self = [super init];    if(self){        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(say:) name:@"message" object:nil];    }    return self;}-(void)say:(NSNotification *)notification{    NSDictionary *dic = [notification userInfo];    NSLog(@"%@",[dic objectForKey:@"name"]);}-(void)dealloc{    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"message" object:nil];    [super dealloc];}@end

#import <Foundation/Foundation.h>#import "King.h"#import "Worker.h"int main(int argc, const char * argv[]){    King *king = [[King alloc] init];    Worker *worker = [[Worker alloc] init];    [king sendMessage];    [king release];    [worker release];        return 0;}


通知和KVO的区别

KVO只能监听属性的变化,通过NSString类型的属性名来实现。实现了监听,当属性值发生变化时,会自动通知观察者,不用再添加代码了。但是观察者得持有被观察者的引用,以便被观察者注册成为观察者,耦合性太高,不利于代码维护。

NSNotification比较灵活,可以监听内容不局限于属性的变化,还可以对多种多样的状态变化进行监听,监听范围广,使用也灵活。但是需要被观察者手动发送通知,观察者注册监听之后才能进行响应,比KVO多了发送通知的一步。但是观察者注册监听不需要被观察者的引用,没有耦合性,利于代码的维护

0 0
原创粉丝点击