// // NYSerialQueueManager.m // jiaPei // // Created by Ning.ge on 2023/7/2. // Copyright © 2023 JCZ. All rights reserved. // #import "NYSerialQueueManager.h" @interface NYSerialQueueManager () @property (nonatomic, strong) dispatch_queue_t serialQueue; @property (nonatomic, strong) NSMutableArray *tasks; @property (nonatomic, assign) NSUInteger completedTasksCount; @end @implementation NYSerialQueueManager + (instancetype)sharedInstance { static NYSerialQueueManager *instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[NYSerialQueueManager alloc] init]; }); return instance; } - (instancetype)init { self = [super init]; if (self) { _serialQueue = dispatch_queue_create("com.example.NYserialQueue", DISPATCH_QUEUE_SERIAL); _tasks = [NSMutableArray array]; _completedTasksCount = 0; } return self; } - (void)addTask:(void (^)(void))task completion:(void (^)(void))completion { dispatch_async(self.serialQueue, ^{ [self.tasks addObject:task]; dispatch_async(dispatch_get_main_queue(), ^{ if (completion) { completion(); } }); }); } - (void)startCompletion:(void (^)(void))completion { dispatch_async(self.serialQueue, ^{ for (NSUInteger i = 0; i < self.tasks.count; i++) { void (^task)(void) = self.tasks[i]; task(); self.completedTasksCount++; if (self.completedTasksCount == self.tasks.count) { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"All tasks completed."); // 在这里进行任务完成的提示操作 if (completion) { completion(); } }); } } }); } - (void)clear{ self.completedTasksCount = 0; if (self.tasks.count){ [self.tasks removeAllObjects]; } } @end