SPSBNotificationDelegateManager.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // SPSBNotificationDelegateManager.m
  3. // 我的社保
  4. //
  5. // Created by shanp on 2021/4/20.
  6. //
  7. #import "SPSBNotificationDelegateManager.h"
  8. #import <JXHMacro.h>
  9. @implementation SPSBNotificationDelegateManager
  10. + (instancetype)alloc {
  11. NSAssert(![self isMemberOfClass:[SPSBNotificationDelegateManager class]], @"SPSBNotificationDelegateManager is singleton, you should not instantiate it directly.");
  12. return [super alloc];
  13. }
  14. + (SPSBNotificationDelegateManager *)shareManager {
  15. static SPSBNotificationDelegateManager *manager = nil;
  16. static dispatch_once_t once;
  17. dispatch_once(&once, ^{
  18. manager = [[super allocWithZone:nil] init];
  19. manager->_spsb_delegates = NSMutableDictionary.new;
  20. });
  21. return manager;
  22. }
  23. + (instancetype)allocWithZone:(struct _NSZone *)zone {
  24. return [self shareManager];
  25. }
  26. - (void)setDelegate:(id<SPSBNotificationDelegate>)delegate keys:(NSArray<SPSBNotificationDelegateKey> *)keys {
  27. for (SPSBNotificationDelegateKey key in keys) {
  28. [self setDelegate:delegate key:key];
  29. }
  30. }
  31. - (void)removeDelegate:(id<SPSBNotificationDelegate>)delegate keys:(NSArray<SPSBNotificationDelegateKey> *)keys {
  32. for (SPSBNotificationDelegateKey key in keys) {
  33. [self removeDelegate:delegate key:key];
  34. }
  35. }
  36. - (void)setDelegate:(id<SPSBNotificationDelegate>)delegate key:(SPSBNotificationDelegateKey)key {
  37. dispatch_main_async_safe(^{
  38. if (!self->_spsb_delegates[key]) {
  39. self->_spsb_delegates[key] = [NSMapTable weakToStrongObjectsMapTable];
  40. }
  41. [self->_spsb_delegates[key] setObject:key forKey:delegate];
  42. });
  43. }
  44. - (void)removeDelegate:(id<SPSBNotificationDelegate>)delegate key:(SPSBNotificationDelegateKey)key {
  45. dispatch_main_async_safe(^{
  46. if (!self->_spsb_delegates[key]) return;
  47. [self->_spsb_delegates[key] removeObjectForKey:delegate];
  48. if (self->_spsb_delegates[key].count == 0) {
  49. self->_spsb_delegates[key] = nil;
  50. }
  51. });
  52. }
  53. @end
  54. SPSBNotificationDelegateManager *spsb_NotificationDelegateManager() {
  55. return [SPSBNotificationDelegateManager shareManager];
  56. }