在iOS开发中有一个“Notification Center”的概念。这是一个单例对象,允许当事件发生时通知一些对象。它允许我们在低耦合的情况下,满足控制器与一个任意的对象进行通信的目的。
对于一个发出的通知,多个对象能够做出反应,即一对多的方式实现简单。实现一个Notification的步骤如下:
(1)注册通知:addObserver:selector:name:object,并实现触发通知后要实现的操作。
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadJpushData:) name:@"Mynotification"object:nil];
}
- (void)reloadJpushData: (NSNotification *)sender{
//触发通知后执行的操作;
}
(2)发送通知:postNotificationName:object
[[NSNotificationCenter defaultCenter] postNotificationName:@"Mynotification"object:nil];
(3)移除通知:removeObserver:和removeObserver:name:object:
移除某个指定的通知:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"Mynotification" object:self];
移除所有通知:
[[NSNotificationCenter defaultCenter] removeObserver:self];
我现在通过一个Demo来演示如何使用Notification来进行界面间的数据传递。实例代码上传至:https://github.com/chenyufeng1991/iOS-Notification 。
(1)我这里在进行界面返回的时候传递数据,第一个界面的实现如下:
#import "ViewController.h"
#import "inputValue.h"
@interface ViewController()
//使用UITextField返回界面时显示数据;
@property (weak, nonatomic) IBOutlet UITextField *textShowValue;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//在这里注册一个Notification,该Notification的名字为Mynotification,回调方法为displayValue;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(displayValue:) name:@"Mynotification" object:nil];
}
-(void)displayValue:(NSNotification*)value{
//显示该数据;
NSString *str=[value object];
self.textShowValue.text = str;
NSLog(@"%@",str);
}
//按钮点击跳转
- (IBAction)openBtn:(id)sender {
//界面跳转;
inputValue *input = [[inputValue alloc] init];
[self presentViewController:input animated:true completion:nil];
}
@end
(2)第二个界面的实现如下,在这里发送一个通知并传递数据:
#import "inputValue.h"
#import "ViewController.h"
@interface inputValue()
@property (weak, nonatomic) IBOutlet UITextField *textInput;
@end
@implementation inputValue
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)returnBtn:(id)sender {
//在这里发送一个通知,Mynotification这里的名字要和前面注册通知的名字吻合。
[[NSNotificationCenter defaultCenter]postNotificationName:@"Mynotification" object:self.textInput.text];
[self dismissViewControllerAnimated:true completion:nil];
}
@end
(3)运行效果如下:
第二个界面传递数据:
。
第一个界面接收数据:
。
总结,使用Notification传递消息是一对多的关系。我会在接下去继续对Notification的使用进行讲解。
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!