iOS---NSNotification使用解析

来源:互联网 发布:博思软件 编辑:程序博客网 时间:2024/06/04 18:52

一、使用步骤
使用NSNotification很简单, 只要三步
1、添加观察者 在需要的地方注册要观察的通知

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

2、发送通知 在某地方发送通知

NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:self.userNameTextField.text, @"userNameKey", nil];[[NSNotificationCenter defaultCenter] postNotificationName:@"userName" object:self userInfo:dict];

3、移除观察者 移除通知

[[NSNotificationCenter defaultCenter] removeObserver:@"userName"];

二、参数解析

    1、[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"userName" object:nil];    参数说明:               1)观察者,self代表本控制器            2)接收到通知后调用的方法 @selector(update:)            3)通知名称 @"userName"            4)接收哪个发送者的通知。 nil代表接收所有发送者的通知
    2、[[NSNotificationCenter defaultCenter] postNotificationName:@"userName" object:self userInfo:dict];    参数说明:            1)通知名称 @"userName"            2)通知发送者 self            3)附带的信息 dict(如需要传的数据)
 3、[[NSNotificationCenter defaultCenter] removeObserver:@"userName"];    参数说明:            1)通知名称 @"userName"

总结:由此可见都需要通知名称,而且都一样,为了避免通知名称错误,可以写成宏。

三、注意事项
1、注册了观察通知的控制器就要移动要观察的通知。这是因为,当控制器因为某些原因比如内存问题而被销毁的时候,通知中心被注册的该通知还是存在的。而当其他有地方发送该通知的时候,通知中心会继续转发,但是转发的对象已经不存在了,这时候就会crash了。所有有添加就要有移除。

2、有些可能习惯在viewWillAppear和viewWillDisappear方法中配对使用,

- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // 注册通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"userName1" object:nil]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:@"userName1"]; }

不是说不行,但是这两个方法属于会被经常调用的方法,比如左滑右滑的时候会重复调用,还是要多考虑一下业务逻辑,避免不要的坑,
所以建议在viewDidLoad中注册通知,在dealloc中移除通知 (注:在ARC模式下 dealloc不需要 [super dealloc])

- (void)dealloc{    [[NSNotificationCenter defaultCenter] removeObserver:@"userName"];}

3、通知使用比较简单,适用场景 1对多模式 发出一个通知,多个对象监听。

0 0
原创粉丝点击