我想将飞行 API 调用的数量限制为 2。我可以创建一个NSOperationQueue
块并将其添加到队列中,但是每个 API 调用都有一个完成块,所以初始调用是有限的,但我不知道如何限制基于完成块的执行来处理队列。
在下面的代码中,任何时候都可能有超过 2 个调用 API。
NSOperationQueue *requestQueue = [[NSOperationQueue alloc] init];
service.requestQueue.maxConcurrentOperationCount = 2;
for (int i = 0; i < 100; i++)
{
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
[self invokeAPI:kAPIName completion:^BOOL(APIResult *result) {
// Do stuff
}
[requestQueue addOperation:operation];
}
}
将不胜感激任何指向要使用的正确模式的指针。
编辑 - 基于 Marc-Alexandre 的回答
已经创建了这个类来封装操作,从内存的角度来看是一种安全的方法,因为这个类将从 dataAccessService 创建并注入,以及具有对自身的引用的完成块,并且在完成之前调用完成块执行?
@interface MAGApiOperation : NSOperation
@property (nonatomic, strong) id<MAGDataAccessServiceProtocol> dataAccessService;
@property (nonatomic, copy) NSString *apiName;
@property (nonatomic, copy) BOOL (^onCompletion)(APIResult *);
+ (instancetype)apiOperationWithName:(NSString *)apiName dataAccessService:(id<MAGDataAccessServiceProtocol>)dataAccessService completion:(BOOL (^)(APIResult *))onCompletion;
@implementation MAGApiOperation
@synthesize executing = _isExecuting;
@synthesize finished = _isFinished;
#pragma mark - Class methods
/// Creates a new instance of MAGApiOperation
+ (instancetype)apiOperationWithName:(NSString *)apiName dataAccessService:(id<MAGDataAccessServiceProtocol>)dataAccessService completion:(BOOL (^)(APIResult *))onCompletion {
MAGApiOperation *operation = [[self alloc] init];
operation.apiName = apiName;
operation.dataAccessService = dataAccessService;
operation.onCompletion = onCompletion;
return operation;
}
#pragma mark - NSOperation method overrides
- (void)start {
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
if (!self.isCancelled)
{
[self invokeApiWithName:self.apiName completion:self.onCompletion];
}
}
- (void)finish {
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
#pragma mark - Private methods
/// Invokes the api with the name then executes the completion block
- (void)invokeApiWithName:(NSString *)apiName completion:(BOOL (^)(VAAInvokeAPIResult *))onCompletion {
[self.dataAccessService invokeAPI:kAPIName completion:^BOOL(APIResult *result) { {
[self finish];
return onCompletion(result);
}];
}