博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

iOS消息中心与传感

Posted on 2012-12-10 20:40  扬名  阅读(3928)  评论(0编辑  收藏  举报

/* NSNotification.h Copyright (c) 1994-2012, Apple Inc. All rights reserved. */ #import <Foundation/NSObject.h> @class NSString, NSDictionary, NSOperationQueue; /**************** Notifications ****************/ @interface NSNotification : NSObject <NSCopying, NSCoding> - (NSString *)name; - (id)object; - (NSDictionary *)userInfo; @end @interface NSNotification (NSNotificationCreation) + (id)notificationWithName:(NSString *)aName object:(id)anObject; + (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo; @end /**************** Notification Center ****************/ @interface NSNotificationCenter : NSObject { @package void * __strong _impl; void * __strong _callback; void *_pad[11]; } + (id)defaultCenter; - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject; - (void)postNotification:(NSNotification *)notification; - (void)postNotificationName:(NSString *)aName object:(id)anObject; - (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo; - (void)removeObserver:(id)observer; - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject; #if NS_BLOCKS_AVAILABLE - (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block NS_AVAILABLE(10_6, 4_0); // The return value is retained by the system, and should be held onto by the caller in // order to remove the observer with removeObserver: later, to stop observation. #endif @end

1. 观察者observer在消息中心中关注某一事件notification,当事件发生时消息中心给“对该事件感兴趣的观察者”发送消息,即为观察者模式。

2. 要注意的是,注册事件与移除事件是对应的,不能只注册不移除,那样会造成资源泄露。因此一般在已注册的观察者类的dealloc方法中移除本类关心的事件。

3. 给消息中心发送消息是同步的,这意味着在发送消息post函数返回前,消息中心会先把消息分发给各个观察者,最后才返回到post函数。因此一般在观察者收到相应的事件响应后,如果要做非常复杂的操作,那么最好延迟调用复杂操作以使post函数可以尽快返回。

 

设备传感也会给消息中心发送消息

UIKIT_EXTERN NSString *const UIDeviceOrientationDidChangeNotification; // 设备旋转
UIKIT_EXTERN NSString *const UIDeviceBatteryStateDidChangeNotification   NS_AVAILABLE_IOS(3_0);  // 电池状态
UIKIT_EXTERN NSString *const UIDeviceBatteryLevelDidChangeNotification   NS_AVAILABLE_IOS(3_0);  // 电池电量
UIKIT_EXTERN NSString *const UIDeviceProximityStateDidChangeNotification NS_AVAILABLE_IOS(3_0);  // 近距离传感器