接口部分
@interface NotificationCenter : NSObject
+ (void)postNotificationWithName:(NSString *)notificationName;
+ (void)postNotificationWithName:(NSString *)notificationName param:(NSDictionary * __nullable)param;
+ (id <NSObject>)addNotificationOnMainQueueWithName:(NSString *)notificationName block:(void (^)(NSDictionary * __nullable param))block;
+ (void)removeObserver:(id)observer;
+ (void)removeObserver:(id)observer name:(NSString *)name;
+ (void)addNotificationWithObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName;
@end
实现部分
@implementation NotificationCenter
+ (void)postNotificationWithName:(NSString *)notificationName
{
[self postNotificationWithName:notificationName param:nil];
}
+ (void)postNotificationWithName:(NSString *)notificationName param:(NSDictionary *)param
{
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:param];
}
+ (id <NSObject>)addNotificationOnMainQueueWithName:(NSString *)notificationName block:(void (^)(NSDictionary * __nullable param))block
{
return [[NSNotificationCenter defaultCenter] addObserverForName:notificationName object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
NSDictionary *userInfo = note.userInfo;
block(userInfo);
}];
}
+ (void)removeObserver:(id)observer
{
if (observer) {
[[NSNotificationCenter defaultCenter] removeObserver:observer];
}
}
+ (void)removeObserver:(id)observer name:(NSString *)name
{
if (observer) {
[[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:nil];
}
}
+ (void)addNotificationWithObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName
{
[[NSNotificationCenter defaultCenter] addObserver:observer selector:aSelector name:aName object:nil];
}
@end