我正在使用shouldPrepareForSegue
方法,但我遇到了问题
__block BOOL Stat;
if([identifier isEqualToString:@"SignOut"]){
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Are You Sure?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *can = [UIAlertAction actionWithTitle:@"CANCEL" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
Stat = NO;
[alert dismissViewControllerAnimated:YES completion:^{}];
}];
UIAlertAction *sign = [UIAlertAction actionWithTitle:@"SIGN OUT" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
Stat = YES;
NSLog(@"%d",Stat);
}];
[alert addAction:can];
[alert addAction:sign];
[self presentViewController:alert animated:YES completion:^{}];
NSLog(@"%d",Stat);
return Stat;
}else{
return YES;
}
在我响应UIAlertController
之前执行时,
值始终返回0,因为后面的代码首先执行如何防止它。
答案 0 :(得分:1)
如果您正在运行本质上异步的代码,则从调用方法返回一个值将无法正常工作(除非您设置了一些相当复杂的阻塞)。
最好的办法是让呼叫者提供代表或收听通知,而不是取决于返回的值。这样,您就可以触发完成处理程序中发生的任何事情。
答案 1 :(得分:1)
你可以创建一个带有如下所示的完成块的函数,并在你需要的地方调用它,只需检查标志
- (void)signOutWithcompletionHandler:(void (^)(BOOL flag))completionHandler
if([identifier isEqualToString:@"SignOut"]){
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Are You Sure?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *can = [UIAlertAction actionWithTitle:@"CANCEL" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
completionHandler(NO);
[alert dismissViewControllerAnimated:YES completion:^{}];
}];
UIAlertAction *sign = [UIAlertAction actionWithTitle:@"SIGN OUT" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
completionHandler(YES);
NSLog(@"%d",Stat);
}];
[alert addAction:can];
[alert addAction:sign];
[self presentViewController:alert animated:YES completion:^{}];
}else{
completionHandler(YES);
}