gpt4 book ai didi

objective-c - 如何从 iOS 上的 block 显示 UIAlertView?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:31 28 4
gpt4 key购买 nike

从 block 中显示 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. 在 2 个注释行中的任何一个上,直接创建并显示一个UIAlertView,这会使应用程序崩溃,我相信这是由于该 block 是一个异步进程,无法访问用于显示警报的 UI 线程
  2. 在 block 外创建了一个 NSMutableString,用__block,设置在注释行,之后显示。类似的问题在这里, block 是异步运行的,所以在显示警报的时间不能保证NSMutableString 已设置。

谁能提出解决方案?我希望能够以某种方式通知用户,以便他们要么不使用 Twitter,要么离开并在设备设置中设置一个帐户。

谢谢

最佳答案

这是 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];
});
}];

关于objective-c - 如何从 iOS 上的 block 显示 UIAlertView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14137902/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com