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);  // 近距離傳感器

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM