iOS 提供了一种 "同步的" 消息通知机制,观察者只要向消息中心注册, 即可接受其他对象发送来的消息,消息发送者和消息接受者两者可以互相一无所知,完全解耦。
这种消息通知机制可以应用于任意时间和任何对象,观察者可以有多个,所以消息具有广播的性质,只是需要注意的是,观察者向消息中心注册以后,在不需要接受消息时需要向消息中心注销,这种消息广播机制是典型的“Observer”模式。
注册通知:即要在什么地方接受消息
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(mytest:)
name:@"mytest"
object:nil];
参数介绍:
addObserver: 观察者,即在什么地方接收通知;
selector: 收到通知后调用何种方法;
name: 通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。
发送通知:调用观察者处的方法。
[[NSNotificationCenter defaultCenter]
postNotificationName:@"mytest"
object:searchFriendArray];
参数:
postNotificationName:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。
object:传递的参数
注册方法的写法:
- (void) mytest:(NSNotification*) notification
{
id obj = [notification object];//获取到传递的对象
}
注销观察者有2个方法:
a. 最优的方法,在UIViewController.m中:
-(void)dealloc
{
[[NSNotificationCenterdefaultCenter] removeObserver:self];
}
If you see the methodyou don't need to call [super dealloc]; here, only the method without superdealloc needed.
b. 单个移除:
[[NSNotificationCenterdefaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess"object:nil];
//例子 -----根据键盘变化,获取iPhone的不同键盘高度