通知:
- 通知的发布
- 通知的监听
- 通知的移除
NSNotificationCenter
发布通知
-(void)postNotification:(NSNotification *)notification;
可以在notification对象中,设置通知的名称,发布者,额外信息等。
-(void)postNotificationName:(NSString *)name object:(id)obj;
发布1个名称为name的通知,obj为这个通知的发布者。
-(void)postNotificationName:(NSString *)name object:(id)obj userInfo:(NSDictionary *)userInfo;
userInfo: 为额外信息。
监听通知: 监听通知,必须在发布通知之前,必须先监听,再发送通知。
NSNotification,对1个通知的封装。
通知的使用。
// 通知的发布者
// NotificationSender.h
@interface NotificationSender :NSObject
// 通知发布者名称
@property(nanotomic, copy) NSString *name;
@end
//----------------------
// NotificationSender.m
@implementation NotificationSender
@end
// 通知的监听者
// NotificationListener.h
@interface NotificationListener :NSObject
// 接受者名称
@property(nanotomic, copy) NSString *name;
// 监听通知方法, 回调的时候,会自动给参数noteInfo赋值。
-(void)method1:(NSNotification *)noteInfo;
@end
//----------------------
// NotificationListener.m
@implementation NotificationListener
// noteInfo中有:name监听的通知的名称,
// object:监听到的通知是那个对象发布的,
// userInfo: 1个字典,这个字典中包含了通知的具体内容.
- (void)method1:(NSNotification *)noteInfo
{
NSLog(@"-------method1方法被调用");
NSLog(@"%@", noteInfo);
}
- (void)dealloc
{ // 移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 通知的发布者
NotificationSender *sender1 = [[NotificationSender alloc] init];
// 通知的监听者
NotificationListener *listener1 = [[NotificationListener alloc] init];
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
// 监听通知。
// 参数1:要监听通知的对象
// 参数2:该对象的哪个方法,用来监听这个通知
// 参数3:被监听的通知的名称。
// 3.1 当参数3为nil,表示所有的通知,表示凡是sender1对象发布的所有的通知,都会监听到。
// 3.2 如果指定了参数3,指定要监听某个通知,但是没有指定参数4. 那么表示无论是哪个发布的,只要通知名称一样,都会被监听到。
// 3.3 如果参数3和参数4都是nil,所有对象发布的所有的通知,这个方法都会监听到。
// 参数4:发布通知的对象sender1。 方法名称,要带上冒号:
[notificationCenter addObserver:listener1
selector:@selector(method1:)
name:@"tzname1"
object:sender1];
// 通过notificationCenter发布通知。
// 参数1:通知名称
// 参数2:通知的发布者(发布通知的对象)
// 参数3:通知的具体内容
[notificationCenter postNotificationName:@"tzname1"
object:sender1
userInfo:@{
@"title":@"两会准备开始了",
@"content":@"成龙也来参加会议了。"
}];
// 移除通知:当listener1被销毁了。仍然发送通知,还是会调用对象的method1方法,就会野指针错误。
}
return 0;
}