標籤:
NSNotificationCenter是 Cococa訊息中心,統一管理單進程內不同線程的訊息通迅。
添加觀察者接收通知:
//添加通知中樞觀察者[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testMethod:) name:key object:self.person];
參數說明:
addObserver: 觀察者,誰來接收通知;
selector: 收到通知後調用的方法;
name: 註冊所觀察通知的名字
object: 訂閱該通知的對象,如果設定為nil 則接收所有通知
移除註冊觀察者:
//移除某個指定的觀察者 [[NSNotificationCenter defaultCenter] removeObserver:self name:key object:self.person]; //移除所有觀察者 [[NSNotificationCenter defaultCenter] removeObserver:self];
發送通知:
//發送帶參數的通知 NSDictionary *dic [email protected]{@"1":@1,@"2":@2}; [[NSNotificationCenter defaultCenter] postNotificationName:key object:self.person userInfo:dic]; //發送不帶參數的通知 [[NSNotificationCenter defaultCenter] postNotificationName:key object:self.person]; //發送通知對象 NSNotification *notification =[[NSNotification alloc]initWithName:key object:self.person userInfo:nil]; [[NSNotificationCenter defaultCenter]postNotification:notification];
參數說明:
postNotificationName:通知名字 ,和註冊通知觀察者名字一致
object:通知的寄件者
userInfo:通知傳遞的參數
接收通知:
//收到通知後調用方法-(void)testMethod:(NSNotification*)notification{ NSLog(@"notification----->%@",notification);//接收到的通知對象 id sender =[notification object];//擷取寄件者對象 NSLog(@"sender----->%@",sender ); NSDictionary *userInfo=[notification userInfo];//擷取傳遞參數 NSLog(@"userInfo----->%@",userInfo ); }
使用情境:
1.不同頁面之間的通知傳值
IOS學習之NSNotificationCenter訊息機制