iOS中NSNotification浅析

       在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  。欢迎大家访问!

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乞力马扎罗的雪CYF

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值