在NSURLSession
(或NSURLSessionDataTask
)的回調函數/塊(或蘋果術語中的完成處理程序)中,運行檢查函數反對當前的Artist
對象,看看是否所有3個必需的元素都在那裏(如果是,請致電passArtist
)。
無論整理順序如何,如果您這樣做了,最終會調用passArtist
一次獲取3個元素。
這裏有一個簡單的例子來證明Objective-C的的想法(如OP要求):
- (void)getArtistDataWithRequest:(NSURLRequest *)request
{
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
if (error)
{
// Something went wrong, fallback.
NSLog(@"An error occurred: %@", error.localizedDescription);
// You could use some error handler e.g.:
// [self connectionDidFailWithError:error];
return;
}
else if (response)
{
// Seems working, moving forward.
[self connectionDidReceiveSpotifyServerResponse:response
andData:data];
}
}];
[task resume];
}
- (void)connectionDidReceiveSpotifyServerResponse:(NSURLResponse *)aResponse
andData:(NSData *)aResponseData
{
// Do what you want here with the data you get, either it's album, track,
// or whatever.
// Assuming your "Artist" property is named "myArtist", and the "Artist"
// class has a method to process the data you get from Spotify API:
[_myArtist handleArtistData:aResponseData];
// Now check your Artist object's element with another method. e.g.:
if ([_myArtist isLoadingComplete])
{
// Done loading the object, pass it to view controller.
}
// Not yet done, do nothing for now.
}
這僅僅是一個解決方案。一旦你明白了想法,有許多方法可以實現你想要的。
[如何按順序執行兩個異步函數]可能的重複(http://stackoverflow.com/questions/35551771/how-to-execute-two-asynchronous-functions-sequentially) – CouchDeveloper
如果您想調用異步函數_sequentially_ - 即調用#1,等到完成然後檢索結果,調用#2(可能以結果#1作爲參數),等到結束,結果爲#2等 - - 必須有一個完成處理程序或其他方式通知調用者異步函數完成。 SO上已經有很多這樣的問題,也是很好的答案。 – CouchDeveloper
您的問題_may_還可能包含一些特殊的「子問題:有一個_N_輸入數組(例如URL)會得到一個_N_對象數組。獲取每個對象需要調用一個異步函數。在SO上已經被回答了很多次 – CouchDeveloper