FSTDispatchQueue.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <Foundation/Foundation.h>
  17. #import "FSTAssert.h"
  18. #import "FSTDispatchQueue.h"
  19. NS_ASSUME_NONNULL_BEGIN
  20. @interface FSTDispatchQueue ()
  21. - (instancetype)initWithQueue:(dispatch_queue_t)queue NS_DESIGNATED_INITIALIZER;
  22. @end
  23. @implementation FSTDispatchQueue
  24. + (instancetype)queueWith:(dispatch_queue_t)dispatchQueue {
  25. return [[FSTDispatchQueue alloc] initWithQueue:dispatchQueue];
  26. }
  27. - (instancetype)initWithQueue:(dispatch_queue_t)queue {
  28. if (self = [super init]) {
  29. _queue = queue;
  30. }
  31. return self;
  32. }
  33. - (void)verifyIsCurrentQueue {
  34. FSTAssert([self onTargetQueue],
  35. @"We are running on the wrong dispatch queue. Expected '%@' Actual: '%@'",
  36. [self targetQueueLabel], [self currentQueueLabel]);
  37. }
  38. - (void)dispatchAsync:(void (^)())block {
  39. FSTAssert(![self onTargetQueue],
  40. @"dispatchAsync called when we are already running on target dispatch queue '%@'",
  41. [self targetQueueLabel]);
  42. dispatch_async(self.queue, block);
  43. }
  44. - (void)dispatchAsyncAllowingSameQueue:(void (^)())block {
  45. dispatch_async(self.queue, block);
  46. }
  47. #pragma mark - Private Methods
  48. - (NSString *)currentQueueLabel {
  49. return [NSString stringWithUTF8String:dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)];
  50. }
  51. - (NSString *)targetQueueLabel {
  52. return [NSString stringWithUTF8String:dispatch_queue_get_label(self.queue)];
  53. }
  54. - (BOOL)onTargetQueue {
  55. return [[self currentQueueLabel] isEqualToString:[self targetQueueLabel]];
  56. }
  57. @end
  58. NS_ASSUME_NONNULL_END