NYSerialQueueManager.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // NYSerialQueueManager.m
  3. // jiaPei
  4. //
  5. // Created by Ning.ge on 2023/7/2.
  6. // Copyright © 2023 JCZ. All rights reserved.
  7. //
  8. #import "NYSerialQueueManager.h"
  9. @interface NYSerialQueueManager ()
  10. @property (nonatomic, strong) dispatch_queue_t serialQueue;
  11. @property (nonatomic, strong) NSMutableArray *tasks;
  12. @property (nonatomic, assign) NSUInteger completedTasksCount;
  13. @end
  14. @implementation NYSerialQueueManager
  15. + (instancetype)sharedInstance {
  16. static NYSerialQueueManager *instance;
  17. static dispatch_once_t onceToken;
  18. dispatch_once(&onceToken, ^{
  19. instance = [[NYSerialQueueManager alloc] init];
  20. });
  21. return instance;
  22. }
  23. - (instancetype)init {
  24. self = [super init];
  25. if (self) {
  26. _serialQueue = dispatch_queue_create("com.example.NYserialQueue", DISPATCH_QUEUE_SERIAL);
  27. _tasks = [NSMutableArray array];
  28. _completedTasksCount = 0;
  29. }
  30. return self;
  31. }
  32. - (void)addTask:(void (^)(void))task completion:(void (^)(void))completion {
  33. dispatch_async(self.serialQueue, ^{
  34. [self.tasks addObject:task];
  35. dispatch_async(dispatch_get_main_queue(), ^{
  36. if (completion) {
  37. completion();
  38. }
  39. });
  40. });
  41. }
  42. - (void)startCompletion:(void (^)(void))completion {
  43. dispatch_async(self.serialQueue, ^{
  44. for (NSUInteger i = 0; i < self.tasks.count; i++) {
  45. void (^task)(void) = self.tasks[i];
  46. task();
  47. self.completedTasksCount++;
  48. if (self.completedTasksCount == self.tasks.count) {
  49. dispatch_async(dispatch_get_main_queue(), ^{
  50. NSLog(@"All tasks completed.");
  51. // 在这里进行任务完成的提示操作
  52. if (completion) {
  53. completion();
  54. }
  55. });
  56. }
  57. }
  58. });
  59. }
  60. - (void)clear{
  61. self.completedTasksCount = 0;
  62. if (self.tasks.count){
  63. [self.tasks removeAllObjects];
  64. }
  65. }
  66. @end