ALMacros.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // ALMacros.h
  3. // AppLovinSDK
  4. //
  5. // Created by Thomas So on 1/1/22.
  6. //
  7. NS_ASSUME_NONNULL_BEGIN
  8. NS_INLINE BOOL isMainQueue (void)
  9. {
  10. return [NSThread isMainThread];
  11. }
  12. NS_INLINE void deferToNextMainQueueRunloop (void (^block)(void))
  13. {
  14. [[NSOperationQueue mainQueue] addOperationWithBlock: block];
  15. }
  16. NS_INLINE void dispatchOnMainQueueNow (void (^block)(void))
  17. {
  18. dispatch_async(dispatch_get_main_queue(), block);
  19. }
  20. NS_INLINE void dispatchOnMainQueue (void (^block)(void))
  21. {
  22. if ( isMainQueue() )
  23. {
  24. block();
  25. }
  26. else
  27. {
  28. deferToNextMainQueueRunloop(block);
  29. }
  30. }
  31. NS_INLINE void dispatchOnMainQueueImmediate (void (^block)(void))
  32. {
  33. if ( isMainQueue () )
  34. {
  35. block();
  36. }
  37. else
  38. {
  39. dispatchOnMainQueueNow(block);
  40. }
  41. }
  42. NS_INLINE void dispatchOnMainQueueAfter (double delay, dispatch_block_t __nonnull block)
  43. {
  44. if ( delay > 0 )
  45. {
  46. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delay * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
  47. }
  48. else
  49. {
  50. dispatchOnMainQueueImmediate(block);
  51. }
  52. }
  53. NS_INLINE void dispatchOnMainQueueAfterAndDeferToNextMainQueueRunloop (double delay, dispatch_block_t __nonnull block)
  54. {
  55. if ( delay > 0 )
  56. {
  57. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delay * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
  58. }
  59. else
  60. {
  61. deferToNextMainQueueRunloop(block);
  62. }
  63. }
  64. NS_INLINE void dispatchSyncOnMainQueue (dispatch_block_t __nonnull block)
  65. {
  66. // Cannot call dispatch_sync on same queue results in deadlock - so just run op if main queue already
  67. if ( isMainQueue() )
  68. {
  69. block();
  70. }
  71. else
  72. {
  73. dispatch_sync(dispatch_get_main_queue(), block);
  74. }
  75. }
  76. NS_INLINE void dispatchOnGlobalQueueAfter (dispatch_queue_priority_t priority, double delay, dispatch_block_t __nonnull block)
  77. {
  78. dispatch_queue_t globalQueue = dispatch_get_global_queue(priority, 0);
  79. if ( delay > 0 )
  80. {
  81. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delay * NSEC_PER_SEC)), globalQueue, block);
  82. }
  83. else
  84. {
  85. dispatch_async(globalQueue, block);
  86. }
  87. }
  88. NS_ASSUME_NONNULL_END