我是 Swift 的初学者,但是通过代码,我了解到您正在请求“苹果”。如果该请求成功,则再次请求“Oranges”,如果成功,则请求其他水果,依此类推。
是的,您可以使用 NSOperation 链接它们,请参阅我对以下问题的回答,我在其中概述了 2 种不同的方法。
NSOperations 和它们的完成块是否同时运行?
注意:这里有几个场景: 1) 是不是只有“apples”请求成功才请求“oranges”,只有“oranges:请求成功”才请求其他水果?这种情况可以参考上述问题。示例流程如下:
RequestFruitOperation *requestApplesOperation = [[RequestFruitOperation alloc] initWithFruitType:Apples];
[requestApplesOperation setCompletionBlock:^{
if(requestApplesOperation.success){
//add oranges
RequestFruitOperation *requestOrangesOperation = [[RequestFruitOperation alloc] initWithFruitType:Oranges];
[requestOrangesOperation setCompletionBlock:^{
if(requestOrangesOperation.success) {
//add mangoes
RequestFruitOperation *requestMangosOperation = [[RequestFruitOperation alloc] initWithFruitType:Mangos];
[operationQueue addOperation:requestMangosOperation];
}
}];
[operationQueue addOperation:requestOrangesOperation];
}
}
[operationQueue addOperation:requestApplesOperation];
2)如果你可以并行请求“苹果”、“橙子”和“其他水果”,而不需要等待对方成功,那么你不需要将它们链接起来。您可以将操作添加到队列中。
RequestFruitOperation *requestApplesOperation = [[RequestFruitOperation alloc] initWithFruitType:Apples];
[operationQueue addOperation:requestApplesOperation];
RequestFruitOperation *requestOrangesOperation = [[RequestFruitOperation alloc] Oranges];
[operationQueue addOperation:requestOrangesOperation];
RequestFruitOperation *requestMangosOperation = [[RequestFruitOperation alloc] Mangos];
[operationQueue addOperation:requestMangosOperation];