NSNotificationCenter消息中心

發射方:

- (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;



發佈了51 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章