我想将inflight 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创建并注入,以及具有对self的引用的完成块,以及完成在完成块执行 之前调用 ?
@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);
}];
}
答案 0 :(得分:2)
你需要继承NSOperation才能做到这一点。
以下是完整的文档,解释了如何创建NSOperation的子类:https://developer.apple.com/reference/foundation/operation
快速说明:
invokeAPI
来电。[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
self.isExecuting = NO;
self.isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];