我正在尝试理解 Objective-C 中的块。以登录 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];
});
}];
谢谢,迈克