一个完整的通知包含三个属性:
@interface NSNotification : NSObject <NSCopying, NSCoding> @property (readonly, copy)NSString *name;// 通知的名称 @property (readonly, retain) id object;// 通知发布者(是谁要发布通知) @property (readonly, copy) NSDictionary *userInfo;// 一些额外的信息(通知发布者传递给通知接收者的信息内容) @end
发送消息的三种方法:
//发布一个notification通知,可在notification对象中设置通知的名称、通知发布者、额外信息等 - (void)postNotification:(NSNotification *)notification; //发布一个名称为aName的通知,anObject为这个通知的发布者 - (void)postNotificationName:(NSString *)aName object:(id)anObject; //发布一个名称为aName的通知,anObject为这个通知的发布者,aUserInfo为额外信息- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
接收通知(注册通知监听)的两种方法:
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject; //observer:监听器,即谁要接收这个通知//aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入//aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知//anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知 - (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue*)queue usingBlock:(void (^)(NSNotification *note))block; //name:通知的名称//obj:通知发布者//block:收到对应的通知时,会回调这个//blockqueue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行
移除通知的两种方法:
- (void)removeObserver:(id)observer;//移除所有通知 - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;//移除通知名字为aName通知
初始化通知一个通知对象:
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject; + (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
                    
                
                
            
        
浙公网安备 33010602011771号