//這是一個觀察者模式。 //首先在你須要監聽的類中加入觀察者:app
//這個觀察者在監聽到anObject發送名字爲aName的notification時,調用selector的方法,在aSelector方法中獲得userInfo。anObject表示從誰那兒發送出來的消息。好比: [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(onWebClose)name:@"WebClose"object:nil];post
//也就是說監聽到了object:nil發出消息,消息的名字是WebClose,此時observer就調用onWebClose方法。 若是object:nil表示以廣播方式發消息或者獲得消息,這個時候只要消息名字是對的就能夠獲得這個消息。/ 而後在被監聽的類中發送通知:這樣觀察者就接到了消息會調用selector方法; [[NSNotificationCenterdefaultCenter] postNotificationName:@"WebClose"object:nil];ui
最後記得移除這個觀察者: [[NSNotificationCenterdefaultCenter] removeObject:self]; 這個的好處是:徹底兩個不相干的view能夠創建起來聯繫;this
例子代碼: 第一步:建立2個NSNotificationCenter監聽 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:)name:UIApplicationWillResignActiveNotificationobject:nil];rest
//監聽是否觸發home鍵掛起程序 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:)name:UIApplicationDidBecomeActiveNotificationobject:nil]; //監聽是否從新進入程序程序.orm
第二步:實現2個NSNotificationCenter所觸發的事件方法 -(void)applicationWillResignActive:(NSNotification*)notification{
printf("按理說是觸發home按下\n");server
} -(void)applicationDidBecomeActive:(NSNotification*)notification{
printf("按理說是從新進來後響應\n");事件
} 注: 在home鍵觸發後,AppDelegate響應的方法爲: -(void)applicationDidEnterBackground:(UIApplication*)application { Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.rem
}it