发射方:
- (void)publish
{
//单例(唯一)的通知中心
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//通知的内容
NSDictionary *userinfo = @{NewsNotificationTitleKey:@"云南砍人了", NewsNotificationDateKey : @"昨天夜里"};
//通知对象
NSNotification *notificatoin = [NSNotification notificationWithName:NewsNotification object:self userInfo:userinfo];
//发通知
[center postNotification:notificatoin];
}
接收方
@implementation TRReciever
- (instancetype)init
{
self = [super init];
if (self)
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(receive:) name:NewsNotification object:[TRSender defaultTRSender]];
NSNotificationCenter* myCenter = [MySender getNotificationCenter];
[myCenter addObserver:self selector:@selector(receiveMy:) name:NewsNotification object:[MySender getMySender]];
}
return self;
}
- (void)receiveMy:(NSNotification *)notification
{
NSDictionary *dict = notification.userInfo;
NSString *title = [dict valueForKey:NewsNotificationTitleKey];
NSString *date = [dict valueForKey:NewsNotificationDateKey];
NSLog(@"Notification:title:%@, date:%@", title, date);
}
切记用完之后要移除观察者
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;