UIAlertView无法在完成处理程序块中工作。

6
我正在编写代码以获取用户的Twitter帐户访问权限,但在处理设备上没有帐户的情况时遇到了问题。我想做的是显示一个警告,告诉用户为了使用Twitter认证,他们需要先在设置中创建帐户。
以下是我的代码:
self.accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountTypeTwitter = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

[self.accountStore requestAccessToAccountsWithType:accountTypeTwitter options:nil completion:^(BOOL granted, NSError *error) {
    if(granted) {
        //Doesn't matter for the present case
    } else if (error){

        [SVProgressHUD dismiss]; //not directly relevant to the present question, but it also doesn't work within the block, so I'm leaving it as a clue

        switch ([error code]){
            case (6):

                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No Twitter Account Detected" message:@"Please go into your device's settings menu to add your Twitter account." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show]; //triggers an error
                break;

        }
    } 
}];

我不是Xcode调试器的专家,但是显然在ACAccountStoreReply线程中发生了错误,在调用[alert show]后大约25个调用深度,出现了名为ucol_getVersion的进程。调试器显示EXC_BAD_ACCESS(代码=2,地址=0xcc)。
我已经在Stack Overflow和互联网上搜索了关于UIAlertViews在块中不起作用的解决方案,以及有关显示警报的一般问题(我尝试了不同的委托值),以及对requestAccessToAccountsWithType的一般问题。
我还尝试通过阅读各种在线资源以及《Objective-C编程指南》第四版的相关页面来加强对块的理解。
任何帮助都将不胜感激。
1个回答

22

你应该始终确保任何 UI 交互都在主线程中完成。将你的 UIAlertView 调用包装在一个 dispatch_async 中:

dispatch_async(dispatch_get_main_queue(), ^{
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Twitter Account Detected" message:@"Please go into your device's settings menu to add your Twitter account." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
   [alert show];
});

在调用结束时,您还有两个nil


但是如果我想调用此警报视图的委托方法,该怎么办? - Jagveer Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接