IOS之通知

通知是一种发送给一个或者多个观察者,用来通知其在程序中发生了某一个事件的消息。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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值