如何在iOS上的块中显示UIAlertView?

Jim*_*mmy 2 twitter objective-c ios objective-c-blocks ios6

从块中显示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
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过这些解决方案:

  1. 在2个注释行中的任何一行,直接创建并显示UIAlertView,这会导致应用程序崩溃,我相信这是由于块是异步进程而无法访问UI线程来显示警报
  2. 在块外创建一个NSMutableString,标记它 __block,将其设置在注释行上,然后显示.这里的类似问题是块以异步方式运行,因此在显示警报时不能保证NSMutableString已被设置.

谁有人建议解决方案?我希望能够以某种方式通知用户,以便他们可以不使用Twitter,或者在设备设置中关闭并设置帐户.

谢谢

new*_*cct 11

这是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];
    });
}];
Run Code Online (Sandbox Code Playgroud)


小智 8

创建一个显示警报视图的方法,然后在主线程上执行其选择器:

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

称其如下:

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

  • 如果您使用ARC,请务必删除`autorelease`调用. (3认同)