1.通知
2.代理
3.Block
4.KVO
1.通知
1.1 原理:通知中心(NSNotificationCenter)在程序內(nèi)部提供了一種廣播機(jī)制债蜜。把收到的通知根據(jù)內(nèi)部的消息轉(zhuǎn)發(fā)表唠帝,消息轉(zhuǎn)發(fā)給需要的對(duì)象谦炒。所以通知是一種一對(duì)多的消息傳遞方式漾狼。
1.2 使用:
a. 在需要的地方添加要觀察的通知乎婿。
b. 在某地方發(fā)送通知肠阱。
1.3 一般情況下票唆,通知使用在全局性的消息傳遞中,例如登錄是否成功屹徘,秘鑰的保存成功等走趋,在AppleDelegate.m中發(fā)送通知,在控制器里面添加注冊(cè)通知和刪除相應(yīng)的通知噪伊。
消息接收者
/*
1.觀察者(消息接收者)簿煌,self本控制器
2.接收到消息(通知)后調(diào)用的方法
3.接受到通知的名稱(chēng)
4.接收哪個(gè)發(fā)送者通知,nil代表接受所有發(fā)送者的通知
*/
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(fun:) name:@"notificationfun" object:nil];
-(void)fun:(NSNotification *)noti
{
NSLog(@"-----%@",noti.userInfo);
}
//在通知注冊(cè)的地方移除通知
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:@"notificationfun"];
//或者
//盡量不要使用鉴吹,這種移除方式可能會(huì)移除系統(tǒng)的通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
消息發(fā)送者
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6",nil ];
/*
1.通知名稱(chēng)
2.通知發(fā)送者
3.附帶信息
*/
[[NSNotificationCenter defaultCenter]postNotificationName:@"notificationfun" object:self userInfo:dict];