通知(NSNotification)
- ⼀一个完整的通知⼀一般包含3个属性:
- (NSString *)name; // 通知的名称
- (id)object; // 通知发布者(是谁要发布通知)
- (NSDictionary *)userInfo; // ⼀一些额外的信息(通知发布者传递给通知接收者的信息内容)
- 初始化⼀一个通知(NSNotification)对象
+ (instancetype)notificationWithName:(NSString *)aName object:(id)anObject;+ (instancetype)notificationWithName:(NSString*)aNameobject:(id)anObject userInfo:(NSDictionary *)aUserInfo;- (instancetype)initWithName:(NSString *)name object:(id)object userInfo: (NSDictionary *)userInfo;
发布通知
通知中⼼心(NSNotificationCenter)提供了相应的⽅方法来帮助发布通知
● -(void)postNotification:(NSNotification)notification; ➢ 发布⼀一个notification通知,可在notification对象中设置通知的名称、通知发布者、额外信息等 ● -(void)postNotificationName:(NSString)aNameobject:(id)anObject; ➢ 发布⼀一个名称为aName的通知,anObject为这个通知的发布者 ● -(void)postNotificationName:(NSString)aNameobject:(id)anObject userInfo:(NSDictionary )aUserInfo; ➢ 发布⼀一个名称为aName的通知,anObject为这个通知的发布者,aUserInfo为额外信息
创建通知对象
NSNotificationCenter *center = [NSNotificationCenter defaultCenter]
注册通知监听器
-(void)addObserver:(id)observerselector:(SEL)aSelectorname:
(NSString *)aName object:(id)anObject;
observer:监听器,即谁要接收这个通知
aSelector:收到通知后,回调监听器的这个⽅方法,并且把通知对象当做参数传⼊入
aName:通知的名称。如果为nil,那么⽆无论通知的名称是什么,监听器都能收到这个通知
anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知
取消注册通知监听器
- (void)removeObserver:(id)observer;
一般在监听器销毁之前取消注册(如在监听器中加⼊入下列代码):
- (void)dealloc {
//[super dealloc]; ⾮非ARC中需要调⽤用此句
[[NSNotificationCenter defaultCenter] removeObserver:self];
}