main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Goodperson.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Person *p1=[Person new];
Goodperson *g1=[Goodperson new];
[p1 selectPerson];
}
return 0;
}
#import "Person.h"
@implementation Person
- (void)selectPerson
{
NSLog(@"挑选人物中.......");
//我要做什么事情呢?我准备选人,然后把这个消息发出去
//怎么发出去呢?通过通知中心发出去
//1.获取通知中心
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
//2.发送通知
[center postNotificationName:@"selectPerson" object:@{@"selecting":@"IOS"} userInfo:@{@"type":@"man"}];
}
@end
Goodperson.m
#import "Goodperson.h"
@implementation Goodperson
- (instancetype)init //初始化 方法
{
self = [super init];
if (self) {
//3.要接收通知对象
//怎么接收?创建通知中心
NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(receiveNews:) name:@"selectPerson" object:nil];
}
return self;
}
//收到通知后,系统会把通知信息给你.
//收到之后要干什么?
//4.收到之后,执行你的方法
- (void)receiveNews:(NSNotification *)news
{
NSLog(@"通知内容:%@",[news object]);
NSLog(@"通知内容时附带的信息:%@",[ news userInfo]);
NSLog(@"我已经在招人了");
}
//5.对象销毁前,从通知中心移除观察者
- (void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"selectPerson" object:nil];
}
@end