1、通知中心,通知中心有两种方法,一种是发布通知,一种是订阅通知,必须先订阅通知,再发布通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
2、订阅通知
JSPerson*mj = [[JSPerson alloc] init];
mj.name=@"lmj";
JSPerson*nj = [[JSPersonalloc]init];
nj.name=@"lnj";
//必须现有订阅者
//observer通知的订阅者
//aSelector接收到通知后做的事情
//aName要接收的通知的名称,如果为nil 则接收所有通知
//anObject发布者,接收谁发布的通知,如果为nil接收所有人发布的通知
[center addObserver:mj selector:@selector(niuNaiComing:) name:@"mainiumaile" object:nil];
3、发布通知
//现有订阅者,再发布通知
//发布通知sanyuan通知的发布者
[center postNotificationName:@"mainiumaile" object:sanyuan userInfo:@{@"tx":@"好牛奶在三元"}];
[center postNotificationName:@"mainiumaile" object:sanlu userInfo:@{@"tx":@"毒牛奶在三鹿"}];
4、在通知的接收者中处理通知的消息
//noti.object通知的发布者
//noti.userInfo发送者给接受者发送的信息
//noti.name通知的名称
- (void)niuNaiComing:(NSNotification*)noti
{
//noti.name;
//收到的通知的名称
JSCompany*com = noti.object;//通知的发布者
NSLog(@"%@",com.name);
//noti.userInfo; //发布通知的时候发送的额外信息 userInfo:
//NSLog(@"%@",noti);
NSLog(@"%@",noti.userInfo[@"tx"]);
}
5、当订阅者销毁,也要取消订阅通知,否则可能会出现野指针错误;
- (void)dealloc
{
//在arc中不能,也不用调用 [super dealloc];
//取消订阅
/在监听者的dealloc方法中,//必须取消监听,否则,当通知再次出现,通知中心任然回向该监听者发送消息//因为对象已经释放,所以可能会导致崩溃
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
6、通知和代理的区别1、相同点
代理和通知都能完成对象之间的通信(A对象告诉B对象发生了什么,A对象传递数
据给B对象)2、不同点
代理:1对1(1个对象,只能告诉另一个对象发生了什么)
通知:多对多(1个对象可以通知多个对象,1个对象可以订阅多个对象发布的通
知)