在iOS上如何显示UIAlertView?

从块中显示UIAlertView的最好方法是什么?

我在我的代码中有以下操作:

- (IBAction)connectWithTwitterClicked:(id)sender { ACAccountStore * account = [[ACAccountStore alloc]init]; ACAccountType * accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) { if (granted == YES){ NSLog(@"Twitter account has been granted"); NSArray * arrayOfAccounts = [account accountsWithAccountType:accountType]; if([arrayOfAccounts count] > 0){ ACAccount * twitterAccount = [arrayOfAccounts lastObject]; NSLog(@"Found twitter Id of [%@]", twitterAccount.username); // continue on to use the twitter Id } else { // no twitter accounts found, display alert to notify user } } else{ NSLog(@"No twitter accounts have been granted"); // no twitter accounts found, display alert to notify user } }]; } 

到目前为止我已经尝试了这些解

  1. 在两个注释行之一,直接创build并显示一个UIAlertView,这使应用程序崩溃,我相信这是由于块是一个asynchronous过程,并没有访问UI线程来显示警报
  2. 在块外部创build一个NSMutableString,用__block标记它,将它设置在注释行中,然后显示。 类似的问题在这里块是asynchronous运行,所以在显示警报时,不保证NSMutableString已被设置。

任何人都可以提出解决scheme 我希望能够以某种方式通知用户,以便他们可以不使用twitter,或者在设备设置中closures并设置帐户。

谢谢

创build一个显示alert视图的方法,然后在主线程上执行select器:

 - (void)showAlertWithTitle:(NSString *)t { [[[[UIAlertView alloc] initWithTitle:t message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ] autorelease] show]; } 

如下所示:

 [SomeClass dispatchNastyAsyncBlock:^{ // ... do stuff, then [self performSelectorOnMainThread:@selector(showAlertWithTitle:) withObject:@"Here comes the title" waitUntilDone:YES]; }]; 

这是GCD的方式:

 [SomeClass dispatchNastyAsyncBlock:^{ // ... do stuff, then dispatch_async(dispatch_get_main_queue(), ^ { [[[[UIAlertView alloc] initWithTitle:t message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ] autorelease] show]; }); }];