IOS 消息中心机制

 
/* 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);  // 近距离传感器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值