消息通知的三种方式总结

通知允许我们在低程度耦合的情况下,满足控制器与一个任意的对象进行通信的目的。 这种模式的基本特征是为了让其他的对象能够接收到某种事件传递过来的通知,主要使用通知名称来发送和接收通知。

当两个子系统有直接关系,可以考虑闭包、代理等方法传值,单如果两个子系统是独立的,没有耦合关系,此时,就需要另一种形式,通知 Notification.

通知的优势和缺点

优势:

  1. 不需要编写多少代码,实现比较简单;

  2. 对于一个发出的通知,多个对象能够做出反应,简单实现一对多的方式,较之于 Delegate 可以实现更大的跨度的通信机制;

  3. 能够传递参数(object 和 userInfo),object 和 userInfo 可以携带发送通知时传递的信息。

缺点:

  1. 在编译期间不会检查通知是否能够被观察者正确的处理;

  2. 在释放通知的观察者时,需要在通知中心移除观察者;

  3. 在调试的时候,通知传递的过程很难控制和跟踪;

  4. 发送通知和接收通知时需要提前知道通知名称,如果通知名称不一致,会出现不同步的情况;

  5. 通知发出后,不能从观察者获得任何的反馈信息。

NSNotification 的三种使用方式实例分析:

1.发送通知,不传递参数;

发送通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"notification1" object:nil];

接收(监听)通知:

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

方法调用:

- (void)notificationEvent
{
    NSLog(@"接收不带参数的消息");
}

移除观察者:

-(void)dealloc
{
    //移除观察者,Observer不能为nil
    [[NSNotificationCenter defaultCenter] removeObserver: self name:@"notification1" object: nil];
}

2.使用 object 传递消息 ;

发送通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"notification2" object:[NSString stringWithFormat:@"%@",self.titleLabel.text]];

接收(监听)通知:

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

方法调用:

-(void)notificationEvent:(NSNotification *)noti
{
    //使用object处理消息
    NSString *info = [noti object];
    NSLog(@"接收 object传递的消息:%@",info);
}

移除观察者:

-(void)dealloc
{
    //移除观察者,Observer不能为nil
    [[NSNotificationCenter defaultCenter] removeObserver: self name:@"notification2" object: nil];
}

3.使用 userInfo 传递消息;

发送通知:

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.indexPath,@"indexPath",self.subCommentArray[indexPath.row].ID,@"replyID", nil];
// 通知到详情界面
[[NSNotificationCenter defaultCenter] postNotificationName:@"showInputTitleViewAndRaiseCommentViewWhenReplyToReply" object:nil userInfo:dic];

接收(监听)通知:

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

方法调用:

- (void)notificationEvent:(NSNotification *)noti
{
    //使用userInfo处理消息
    NSDictionary *dic = [noti userInfo];
    NSIndexPath *indexPath = [dic objectForKey:@"indexPath"];
    NSString *replyID = [dic objectForKey:@"replyID"];
}

移除观察者:

-(void)dealloc
{
    //移除观察者,Observer不能为nil
    [[NSNotificationCenter defaultCenter] removeObserver: self name:@"notification3" object: nil];
}

注意点: [[NSNotificationCenter defaultCenter] removeObserver: ] 方法为移除系统通知。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值