這裏是如何做到的任意數量的非同步請求,並知道他們什麼時候完成:
(1)代表的東西,他們參數化的要求。在你的情況下,請求由頁碼錶示。
NSArray *pages = @[ @1, @2, @3 /* ... */ ];
(2)表示具有該請求的參數與非同步操作的結果相關聯的詞典的結果:
NSMutableDictionary *results = [@{} mutableCopy];
(3)的遞歸算法做的事情的列表是這樣這個:如果列表是空的,我們完成了,否則,在列表中做第一件事,然後做其餘的列表。在代碼中,你會打電話:
[self getPages:pages filling:results completion:^(BOOL success) {
// here, we can update our UI
// collecting the results in a dictionary allows us to know
// which result goes with which request
}];
- (void)getPages:(NSArray *)pages filling:(NSMutableDictonary *)results completion:(void (^)(BOOL))completion {
NSInteger count = pages.count;
// degenerate case is an empty array which means we're done
if (!count) return completion(YES);
// otherwise, do the first operation on the to do list, then do the remainder
NSNumber *page = pages[0];
NSArray *remainder = [pages subarrayWithRange:NSMakeRange(0, count-1)];
[self getRequest:[page intValue] completion:^(BOOL *success, int data) {
if (success) {
results[page] = @(data);
[self getPages:remainder filling:results completion:completion];
} else {
completion(NO);
}
}];
}
注意,爲了使用NS集合,我們「包裝」頁碼int
S和返回int
S作爲NSNumber
。但結果將是這樣的:
@{ @1 : @42, @2 : @154, etc...
凡@ 42 @和154的NSNumber包裹由您調用getRequest完成塊返回整數。
爲什麼不分開調用getRequest:[自我調用getRequest完成:^(BOOL成功,int數據){ [dataArray中ADDOBJECT:數據];}]; [self getRequest completion:^(BOOL succeeded,int data){ [dataArray addObject:data];}]; – anhtu
我經常看到這個問題,並用不同的化身來回答它... http://stackoverflow.com/questions/31897706/how-to-create-an-array-of-uiimages/31898423#31898423。讓我知道這是否足夠具體到你的情況。如果沒有,我可以定製。 – danh
@anhtu,OP希望知道所有請求何時完成。 – danh