2011年2月16日 星期三

【IOS】消息通信機制NSNotificationCenter


最近寫程序需要用到這類,研究了下,現把成果和大家分享。
NSNotificationCenter是專門供程序中不同類間的消息通信而設置的,使用起來極為方便,

設置通知,就是說要在什麼地方(哪個類)接受通知,一般在初始化中做。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) name:@" test" object:nil];
我僅對以上參數做以說明:addObserver 這個是觀察者,就是說 在什麼地方接收通知;
 selector 這個是收到通知後,調用何種方法;
 name: 這個是通知的名字,也是通知的唯一標示,編譯器就通過這個找到通知的。
發送通知,就是說此時要調用觀察者處的方法。
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:searchFriendArray];
我僅對以上參數做以說明:
postNotificationName:通知的名字,也是通知的唯一標示,編譯器就通過這個找到通知的。
object:傳遞的參數
發送通知時,默認調用test方法。
- (void) test:(NSNotification*) notification
{
searchFriendArrary = [notification object];//通過這個獲取到傳遞的對象
}

3 則留言: