参考地址:http://blog.csdn.net/leochang130731/article/details/17082125
参考书籍:ios7 programming cookbook
Three types of notifications are available in iOS:
1. A normal notification (an instance of NSNotification class)
This is a simple notification that your app can broadcast to all possible receivers inside your app. iOS also broadcasts notifications of this type to your app while your app is in the foreground, informing you of various system events that are happening, such as the keyboard showing or being hidden. These notifications are great for decoupling code, in that they can allow you to cleanly separate various components in a complex iOS application.
这种类型通过NSNotificationCenter类来管理通知,都是应用在APP处于foreground或者activate状态,它的应用场景有两个:
(1)App内部不同模块间传递数据。(这个跟delegate有点类似)
发送方通过[[NSNotificationCenter defaultCenter] postNotification:notification]来发送消息,数据放在notification里。需要数据的接收方注册这个通知,[[NSNotificationCenter defaultCenter] addObserver:self name:name object:obj]]。
(2)监听系统事件。
APP处于前台时,监听比如键盘显示、键盘隐藏等事件。
键盘升起 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
键盘降下[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2. A local notification (an instance of UILocalNotification class)
This is a notification that you schedule to be delivered to your app at a specific time.Your app can receive it even if the app is in the background or not running at all,and the app is started if the notification is delivered while your app is not running.You would normally schedule a local notification if you want to ensure that your app gets woken up (granted that the user permits this action, as we will see later) at a specific time of the day.
本地通知主要用于基于时间的提醒通知,由系统的notification center来统一管理。即使APP处于后台或者没有启动,也能接收到通知。调用方法:[[UIApplication sharedApplication] scheduleLocalNotification:notification]。另一个就是,当APP处于后台或者没有启动,监听系统事件,这个时候NSNotificationCenter无能为力。
3. Push notifications
This is a notification that is sent to an iOS device via a server. It is called a push notification because your app doesn’t have to keep polling a server for notifications. iOS maintains a persistent connection to Apple Push Notification Services servers (APNS servers), and whenever a new push message is available, iOS will process the message and send it to the app to which the push was designated.
远程通知,则是由服务器下发。
本地通知和远程通知是通过Notification Center来管理的,自从iOS5起才提供。Notification Center包含一个窗口,当我们按住status bar上面,然后下拉就可以看到很多消息,比如微博消息、QQ推送消息等。注意:Notification Center仅用来用来管理UILocalNofication和Remote Notification的通知。 来自NSNotificationCenter的消息(应用内部消息)不是由Notification Center管理的。三种类型的notification作用各不相同。
很不幸的时NSNotificationCenter和Notification Center共享了一个名字,但是他们没有关系。下图总结了三种类型notification的区别: