iOS 通知notification

本文介绍iOS中使用Notification(单例类)实现一对多的通知机制,通过观察者模式让多个页面响应同一通知。提供了三个页面间跳转并响应背景颜色变化的具体代码示例。

ios通知
Notification(单例类)
是一对多的实现,观察者模式

参考如下链接:
http://www.th7.cn/Program/IOS/201406/212434.shtml

举例:
三个页面的跳转:
//页面一

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    //挂出通知change,实现方法为didNotification

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

    

}


- (void)didNotification{


    self.view.backgroundColor = [UIColor redColor];

}


- (void)didReceiveMemoryWarning {

    

    [super didReceiveMemoryWarning];


}


@end

//页面2

#import "firstPageViewController.h"


@interface firstPageViewController ()


@end


@implementation firstPageViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    //同页面一,挂出通知,实现方法为didChange

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

//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"change" object:nil];

}


- (void)didChange{

    self.view.backgroundColor = [UIColor greenColor];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}


@end


//页面3

#import "secondViewController.h"


@interface secondViewController ()


@end


@implementation secondViewController


- (void)viewDidLoad {

    [super viewDidLoad];

}

- (IBAction)didChange:(id)sender {

    //创建一个通知类型对象

    NSNotification *notification = [NSNotification notificationWithName:@"change" object:nil userInfo:nil];

    //使用通知

    [[NSNotificationCenter defaultCenter] postNotification:notification];


}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}


@end


storyboard布局见图

当按下第一个页面的button时跳转到页面二,按下页面二的button时跳转到页面三,按下页面三的change按钮,改变相应的背景颜色。

这样可以快速方便的实现多个对象实现统一功能的操作




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值