一般咱們在 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; }