STNotifications 是一个为强类型通知的 Objective-C 库
功能
- 强类型有效负载(使用 Objective-C 轻量级泛型周围的 API 进行操作)
- 确保通知和观察者只有一个 NSNotificationName 存在
- 您可以从接收到的通知中获取发送者的指针!
- 与 Swift 兼容
- 在 NotificationToken 分配释放时自动注销订阅!
使用方法
创建工厂方法
#import <STNotifications/STNotifications.h>
@class Alert;
@interface STNotificationFactory (YourCustomNotifications)
+ (STNotificationFactory<Payload *> *)payloadFactory;
@end
@implementation STNotificationFactory (YourCustomNotifications)
+ (STNotificationFactory<Payload *> *)payloadFactory {
return [STNotificationFactory factoryWithNotificationName:@"Notification payload"];
}
@end
或者您的子类
#import <STNotifications/STNotifications.h>
#import "Alert.h"
@interface AlertNotificationFactory : STNotificationFactory <Alert *>
- (instancetype)init;
+ (instancetype)factory;
@end
@implementation AlertNotificationFactory
- (instancetype)init {
return self = [super initWithNotificationName:@"AlertNotification"];
}
+ (instancetype)factory {
return [[AlertNotificationFactory alloc] init];
}
@end
就这样!现在您的 NotificationName 和有效负载类型就不会再出错了!
开始观察
自动完成功能将按照与 NSArray 中相同的方式插入您在工厂中指定的有效载荷类型!
@property (strong, nonatomic) STNotificationToken *token; // < ---- Auto Unsubscription on deallocation!
...
let factory = [AlertNotificationFactory new];
let alertObserver = [factory makeObserverWithOnRecievedBlock:^(STNotification<Alert *> * _Nullable notification) {
NSLog(@"%@", notification.payload.message);
NSLog(@"%@", notification.sender);
}];
self.alertToken = [[NSNotificationCenter defaultCenter] stn_addNotificationObserver:alertObserver];
您可追踪通知的发送者! STNotificationToken 在释放时具有自动退订功能!
发布通知
var alert = [Alert new];
alert.message = @"ALARM!!!";
let alertFactory = [AlertNotificationFactory new];
let alertNotification = [alertFactory makeNotificationWithPayload:alert sender:self];
[[NSNotificationCenter defaultCenter] stn_postNotification:alertNotification];
安装
CocoaPods
target '<Your Target Name>' do
pod 'STNotifications', '~> 1.1.5.1'
end
Carthage
github "neisip/StronglyTypedNotifications"
许可协议
STNotifications 采用 MIT 许可协议发布。 查看 LICENSE 详细信息