我試圖理解Objective-C中的塊。舉例來說,登錄到Twitter。我希望主線程等待塊完成。瞭解塊(使用twitter登錄)
如何在下面的代碼中實現此目的。 showMain方法正在轉換到下一個視圖。數組TweetArray爲空,因爲異步塊沒有完成。現在,我使用方法performSelectorOnMainThread:withObject:waitUntilDone :.請詳細解釋塊的概念。
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
if (granted)
{
NSArray *accounts = [account accountsWithAccountType:accountType];
// Check if the users has setup at least one Twitter account
if (accounts.count > 0)
{
ACAccount *twitterAccount = [accounts objectAtIndex:0];
SLRequest *twitterInfoRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:@"https://api.twitter.com/1.1/users/show.json"] parameters:[NSDictionary dictionaryWithObject:twitterAccount.username forKey:@"screen_name"]];
[twitterInfoRequest setAccount:twitterAccount];
// Making the request
[twitterInfoRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if ([urlResponse statusCode] == 429) {
return;
}
if (error) {
return;
}
// Check if there is some response data
if (responseData) {
NSError *error = nil;
NSArray *TweetArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSLog(@"%@", TweetArray);
}
});
}];
}
} else {
NSLog(@"Access denied");
}
});
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self performSelectorOnMainThread:@selector(showMain) withObject:nil waitUntilDone:YES];
});
}];
謝謝, 邁克
*請詳細解釋塊的概念* ***略微***太寬,無法正確回答。抓住一本Objective-C書,閱讀塊章節,回來一個更狹窄的問題。 –