OSSCancellationTokenRegistration.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2014, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. #import "OSSCancellationTokenRegistration.h"
  11. #import "OSSCancellationToken.h"
  12. NS_ASSUME_NONNULL_BEGIN
  13. @interface OSSCancellationTokenRegistration ()
  14. @property (nonatomic, weak) OSSCancellationToken *token;
  15. @property (nullable, nonatomic, strong) OSSCancellationBlock cancellationObserverBlock;
  16. @property (nonatomic, strong) NSObject *lock;
  17. @property (nonatomic) BOOL disposed;
  18. @end
  19. @interface OSSCancellationToken (OSSCancellationTokenRegistration)
  20. - (void)unregisterRegistration:(OSSCancellationTokenRegistration *)registration;
  21. @end
  22. @implementation OSSCancellationTokenRegistration
  23. + (instancetype)registrationWithToken:(OSSCancellationToken *)token delegate:(OSSCancellationBlock)delegate {
  24. OSSCancellationTokenRegistration *registration = [OSSCancellationTokenRegistration new];
  25. registration.token = token;
  26. registration.cancellationObserverBlock = delegate;
  27. return registration;
  28. }
  29. - (instancetype)init {
  30. self = [super init];
  31. if (!self) return self;
  32. _lock = [NSObject new];
  33. return self;
  34. }
  35. - (void)dispose {
  36. @synchronized(self.lock) {
  37. if (self.disposed) {
  38. return;
  39. }
  40. self.disposed = YES;
  41. }
  42. OSSCancellationToken *token = self.token;
  43. if (token != nil) {
  44. [token unregisterRegistration:self];
  45. self.token = nil;
  46. }
  47. self.cancellationObserverBlock = nil;
  48. }
  49. - (void)notifyDelegate {
  50. @synchronized(self.lock) {
  51. [self throwIfDisposed];
  52. self.cancellationObserverBlock();
  53. }
  54. }
  55. - (void)throwIfDisposed {
  56. NSAssert(!self.disposed, @"Object already disposed");
  57. }
  58. @end
  59. NS_ASSUME_NONNULL_END