iOS 构建项目的通知中心
以我现在的项目组的通知中心为例
FNAgendaNotification.h
#import <Foundation/Foundation.h> @class FNAgendaModel; @class FNAgendaLabelModel; @interface FNAgendaNotification : NSObject + (void)receivedWarnNotification:(NSDictionary *)notifi; + (void)notifyAgendaLabelChanged; //通知传对象 + (void)addNewAgendaLabelChanged:(FNAgendaLabelModel *)agendaLabelModel; @end
FNAgendaNotification.m
#define FNNotification(x) NSString *x = @#x #import "FNAgendaNotification.h" #import "FNAgendaModel.h" #import "FNAgendaLabelModel.h" FNNotification(kFNNotificationReceivedAgendaSystemNotifi); FNNotification(kFNNotificationReceivedAgendaWarnNotifi); FNNotification(kFNNotificationAgendaLabelChanged); @implementation FNAgendaNotification + (void)receivedWarnNotification:(NSDictionary *)notifi { [[NSNotificationCenter defaultCenter] postNotificationName:kFNNotificationReceivedAgendaWarnNotifi object:nil userInfo:notifi]; } + (void)notifyAgendaLabelChanged { [[NSNotificationCenter defaultCenter] postNotificationName:kFNNotificationAgendaLabelChanged object:nil userInfo:nil]; } + (void)addNewAgendaLabelChanged:(FNAgendaLabelModel *)agendaLabelModel { [[NSNotificationCenter defaultCenter] postNotificationName:kFNNotificationAgendaLabelAddNewLabel object:agendaLabelModel userInfo:nil]; } @end
这样通知中心就搭建好了
然后就是在需要的地方发送通知了
//第一种通知 [FNAgendaNotification receivedWarnNotification:body]; //第二种通知 [FNAgendaNotification notifyAgendaLabelChanged]; //第三种通知 [FNAgendaNotification addNewAgendaLabelChanged:labelModel];
最后一步,在需要接受通知的地方 实现接受通知后的方法
一般是写一个方法里面放所有需要在这个页面监测的通知
在viewDidLoad中调用 addListenEvents 方法就可以了 #pragma mark - 监听处理 - (void)addListenEvents { //第一种通知 extern NSString *kFNNotificationReceivedAgendaWarnNotifi; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFNAgendaWarnSystemNotify:) name:kFNNotificationReceivedAgendaWarnNotifi object:nil]; //第二种通知,不传值 extern NSString *kFNNotificationAgendaLabelChanged; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAgendaLabelListChanged:) name:kFNNotificationAgendaLabelChanged object:nil]; //第三种通知,传对象 extern NSString *kFNNotificationAgendaLabelAddNewLabel; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAddNewAgendaLabel:) name:kFNNotificationAgendaLabelAddNewLabel object:nil]; } - (void)onFNAgendaWarnSystemNotify:(NSNotification *)notification { NSDictionary *userInfo = [notification userInfo]; } - (void)onAgendaLabelListChanged:(NSNotification *)notification { } - (void)onAddNewAgendaLabel:(NSNotification *)notification { FNAgendaLabelModel *agendaLabelModel = notification.object; }