發射方:
- (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;