1、顺序请求数据
在开发中,数据请求可能需要进行逐步逐个进行。需要用到NSOperationQueue。具体如下:
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
//默认创建的信号为0
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//这里是请求的方法(自定义或者AFN)
[[ZSKNNetworking shareInstance] requestDataWithBusCode:@"" TransactionID:@""
TimeStamp:@"" ReqInfo:productLabelReqInfo type:(HttpRequestTypeGet)
success:^(id responseObject) {
//这里请求成功信号量 +1 为1
dispatch_semaphore_signal(semaphore);
} failure:^(NSError *error) {
//这里请求成功信号量 +1 为1
dispatch_semaphore_signal(semaphore);
}];
}];
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
//默认创建的信号为0
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//这里是请求的方法(自定义或者AFN)
[[ZSKNNetworking shareInstance] requestDataWithBusCode:@"" TransactionID:@""
TimeStamp:@"" ReqInfo:productLabelReqInfo type:(HttpRequestTypeGet)
success:^(id responseObject) {
//这里请求成功信号量 +1 为1
dispatch_semaphore_signal(semaphore);
} failure:^(NSError *error) {
//这里请求成功信号量 +1 为1
dispatch_semaphore_signal(semaphore);
}];
}];
NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
//默认创建的信号为0
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//这里是请求的方法(自定义或者AFN)
[[ZSKNNetworking shareInstance] requestDataWithBusCode:@"" TransactionID:@""
TimeStamp:@"" ReqInfo:productLabelReqInfo type:(HttpRequestTypeGet)
success:^(id responseObject) {
//这里请求成功信号量 +1 为1
dispatch_semaphore_signal(semaphore);
} failure:^(NSError *error) {
//这里请求成功信号量 +1 为1
dispatch_semaphore_signal(semaphore);
}];
}];
//这是顺序执行方法
[operation2 addDependency:operation1];
[operation3 addDependency:operation2];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//放入到队列中
[queue addOperations:@[operation1, operation2, operation3] waitUntilFinished:NO];
//添加关于信号量的监听通知
[queue addObserver:self forKeyPath:@"operationCount" options:0 context:nil];
以上是在方法中的内容。
//添加监听(数据请求)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"operationCount"]) {
NSOperationQueue *queue = (NSOperationQueue *)object;
if (queue.operationCount == 0) {
NSLog(@"全部完成");
}
}
}
网友评论