NSObject+CommonBlock.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. //
  2. // NSObject+CommonBlock.m
  3. // CommonLibrary
  4. //
  5. // Created by Alexi on 3/11/14.
  6. // Copyright (c) 2014 CommonLibrary. All rights reserved.
  7. //
  8. #import "NSObject+CommonBlock.h"
  9. @implementation NSObject (CommonBlock)
  10. - (void)excuteBlock:(CommonBlock)block
  11. {
  12. __weak id selfPtr = self;
  13. if (block) {
  14. block(selfPtr);
  15. }
  16. }
  17. - (void)performBlock:(CommonBlock)block
  18. {
  19. if (block)
  20. {
  21. [self performSelector:@selector(excuteBlock:) withObject:block];
  22. }
  23. }
  24. - (void)performBlock:(CommonBlock)block afterDelay:(NSTimeInterval)delay
  25. {
  26. if (block)
  27. {
  28. [self performSelector:@selector(excuteBlock:) withObject:block afterDelay:delay];
  29. }
  30. }
  31. - (void)cancelBlock:(CommonBlock)block
  32. {
  33. [[NSRunLoop currentRunLoop] cancelPerformSelector:@selector(excuteBlock:) target:self argument:block];
  34. }
  35. - (void)excuteCompletion:(CommonCompletionBlock)block withFinished:(NSNumber *)finished
  36. {
  37. __weak id selfPtr = self;
  38. if (block) {
  39. block(selfPtr, finished.boolValue);
  40. }
  41. }
  42. - (void)performCompletion:(CommonCompletionBlock)block withFinished:(BOOL)finished
  43. {
  44. if (block)
  45. {
  46. [self performSelector:@selector(excuteCompletion:withFinished:) withObject:block withObject:[NSNumber numberWithBool:finished]];
  47. }
  48. }
  49. - (void)cancelCompletion:(CommonCompletionBlock)block
  50. {
  51. [[NSRunLoop currentRunLoop] cancelPerformSelector:@selector(excuteCompletion:withFinished:) target:self argument:block];
  52. }
  53. - (void)asynExecuteCompletion:(CommonBlock)completion tasks:(CommonBlock)task, ... NS_REQUIRES_NIL_TERMINATION
  54. {
  55. va_list arguments;
  56. if (task)
  57. {
  58. if (task)
  59. {
  60. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  61. if (task)
  62. {
  63. task(self);
  64. }
  65. });
  66. va_start(arguments, task);
  67. BOOL next = YES;
  68. do
  69. {
  70. CommonBlock eachObject = va_arg(arguments, CommonBlock);
  71. if (eachObject)
  72. {
  73. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  74. if (eachObject)
  75. {
  76. eachObject(self);
  77. }
  78. });
  79. }
  80. else
  81. {
  82. next = NO;
  83. }
  84. }while (next);
  85. va_end(arguments);
  86. }
  87. dispatch_barrier_async(dispatch_get_global_queue(0, 0), ^{
  88. if (completion)
  89. {
  90. completion(self);
  91. }
  92. });
  93. }
  94. }
  95. @end