NSNotificationCenter主要用於廣播訊息到多個監聽著,其傳統用法
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethod:) name:kMyNotificationIdentifier object:nil]; 5 } 6 7 - (void)dealloc 8 { 9 [[NSNotificationCenter defaultCenter] removeObserver:self]; 10 } 11 12 - (void)someMethod:(NSNotification *)note 13 { 14 // Message received 15 }
利用Blocks操作
@implementation MyViewController { id _notificationObserver; } // ... - (void)viewDidLoad { [super viewDidLoad]; _notificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kMyNotificationIdentifier object:nil queue:nil usingBlock:^(NSNotification *note) { // message received }]; } // dealloc, or potentially a method popping this view from the stack - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:_notificationObserver]; }