1.基本概念
IOS中经常会使用到NSNotification和Delegate来进行一些类之间的消息传递,NSNotification就是IOS提供的一个消息中心,有一个全局的defaultNotification管理应用中的消息机制。里面使用的是一个观察者,通过注册addObserver和解除注册removeObserver来实现消息传递。在类析构的时候,需要removeObserver,不然就会引发崩溃,但NSNotification是一对多的。
而Delegate,就是通过增加一个指针,然后把需要调用的函数通过delegate传递到其他类中,不需要通过广播的形式去实现,但是delegate的形式只能是一对一的,不能实现一对多。
从效率上看,Delegate是轻量级的,NSNotification则是重量级的,效率上delegate明显要比NSNotification高。
使用上,如果A和B相关联,则在A和B之间建立Delegate进行联系。
如果A和B是两个不相干的类,A不知道B,B也不知道A,则通过NSNotication进行联系。
2.系统自带NSNotification示例
@interface ViewController ()
//代理类
@property (nonatomic, strong) UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.