VLCDBChangeNotifier.m 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // VLCDBChangeNotifier.m
  3. // VLC for iOS
  4. //
  5. // Created by Tobias Conradi on 01.04.15.
  6. // Copyright (c) 2015 VideoLAN. All rights reserved.
  7. //
  8. #import "VLCDBChangeNotifier.h"
  9. #import <notify.h>
  10. @interface VLCDBChangeNotifier ()
  11. @property (nonatomic, strong) NSMapTable *observers;
  12. @property (nonatomic, assign) int notification_token;
  13. @end
  14. @implementation VLCDBChangeNotifier
  15. - (id)init
  16. {
  17. self = [super init];
  18. if (self) {
  19. self.observers = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPointerPersonality valueOptions:NSPointerFunctionsCopyIn];
  20. }
  21. [self startListening];
  22. return self;
  23. }
  24. - (void)dealloc {
  25. notify_cancel(_notification_token);
  26. }
  27. + (instancetype)sharedNotifier
  28. {
  29. static dispatch_once_t onceToken;
  30. static VLCDBChangeNotifier *instance;
  31. dispatch_once(&onceToken, ^{
  32. instance = [VLCDBChangeNotifier new];
  33. });
  34. return instance;
  35. }
  36. - (void)addObserver:(id)observer block:(void (^)(void))onUpdate {
  37. [self.observers setObject:onUpdate forKey:observer];
  38. }
  39. - (void)removeObserver:(id)observer {
  40. [self.observers removeObjectForKey:observer];
  41. }
  42. - (void)dbDidChange {
  43. for (void(^onUpdate)() in self.observers.objectEnumerator) {
  44. onUpdate();
  45. }
  46. }
  47. - (void)startListening {
  48. const char *notification_name = "org.videolan.ios-app.dbupdate";
  49. dispatch_queue_t queue = dispatch_get_main_queue();
  50. int registration_token;
  51. __weak typeof(self) weakSelf = self;
  52. notify_register_dispatch(notification_name, &registration_token, queue, ^ (int token) {
  53. [weakSelf dbDidChange];
  54. });
  55. self.notification_token = registration_token;
  56. }
  57. @end