一般咱们在 iOS 中发生什么事件时该作什么是由 Delegate 实现的,例如 View 加载完后会触发 viewDidLoad。 Apple 还为咱们提供了另外一种通知响应方式,那就是 NSNotification,系统中(UIKeyboardDidShowNotification 等) 以及某些第三方组件(例如 ASIHTTPRequest 的 kReachabilityChangedNotification 等)。html
NSNotificationCenter 较之于 Delegate 能够实现更大的跨度的通讯机制,能够为两个无引用关系的两个对象进行通讯。NSNotificationCenter 的通讯原理使用了观察者模式:app
@interface classB : NSObject -(void) testNotification; @end @implementation classB -(void) testNotification{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callback:) name:@"TEST" object:nil]; [[NSNotificationCenter defaultCenter] addObserverForName:@"TEST" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) { NSLog(@"%@", [note name]); NSLog(@"%@", [note object]); NSLog(@"%@", [note userInfo]); }]; } -(void) callback:(id)notification{ [self testString]; NSDictionary *info = [notification userInfo]; [info enumerateKeysAndObjectsUsingBlock: ^(id key, id object, BOOL *stop){ //do sth NSLog(@"%@ = %@", key, object); }]; } @end int main(int argc, const char * argv[]) { @autoreleasepool { //test notification classB *b = [[classB alloc] init]; [b testNotification]; [[NSNotificationCenter defaultCenter] postNotificationName:@"TEST" object:nil userInfo:@{@"a":@"hello",@"b":@123}]; } return 0; }
运行结果:函数
2016-05-06 11:24:05.589 test2[65542:7170843] a = hello 2016-05-06 11:24:05.589 test2[65542:7170843] b = 123 2016-05-06 11:24:05.589 test2[65542:7170843] TEST 2016-05-06 11:24:05.589 test2[65542:7170843] (null) 2016-05-06 11:24:05.589 test2[65542:7170843] { a = hello; b = 123; }