参考地址:ios那些事------通知,同志你好
发送通知
1.只是传递动作,不传递具体的信息内容详情
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;
2.传递具体的信息内容,用字典传递
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
式例:一个完整的创建通知的过程:
//发送一个通知,不携带参数
[[NSNotificationCenter defaultCenter] postNotificationName:@“notifyName” object:nil];
//发送一个通知,携带参数
NSDictionary * userInfoDic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"notifyName" object:self userInfo:userInfoDic];
接收通知
1.只是接收动作
2.接收具体的信息内容(同一个方法)
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;
式例:一个完整的接收通知的过程:
1.只是接收动作
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyNameAction) name:@"notifyName" object:nil];
-(void) notifyNameAction
{
}
2.接收具体的信息内容
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyNameAction:) name:@"notifyName" object:nil];
-(void) notifyNameAction:(NSNotification*)notification
{
NSDictionary *dic = notification.userInfo;
NSString *info = dic[@"key"];
}
注销通知
1.注销所有通知
- (void)removeObserver:(id)observer;
2.注销指定通知,一般放在dealloc中
- (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject;
式例:一个完整的注销通知的过程:
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"notifyName"
object:nil];
/*
//非ARC项目
[XXX release];
[super dealloc];//最后调用
*/
}