iOS开发 Block内部如何实现弹框等待输入结果

daniel_xing 2017-07-25 03:59:39
- (void)doSomethingWithBlock:(NSString *(^)())block {
NSLog(@"callback:%@", block());
}
- (void)callMethod {

__weak typeof(self) weakSelf = self;
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_semaphore_t sema = dispatch_semaphore_create(0);

dispatch_async(queue, ^{
[self doSomethingWithBlock:^NSString *{
__block NSString *resultString = nil;
__strong typeof(weakSelf) strongSelf = weakSelf;
// 信号量

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message..." preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:nil];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 获取弹框输入值
resultString = [[alertController.textFields objectAtIndex:0] text];
}]];

[strongSelf presentViewController:alertController animated:YES completion:^{
// 完成信号
dispatch_semaphore_signal(sema);
}];
// 等待
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return resultString;
}];
});
}

这段代码感觉上是没有问题的~ 但是触发callMethod就立即会弹出弹框并输出callback:(null),无奈不知道如何解决,求大神
...全文
165 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
daniel_xing 2017-07-26
  • 打赏
  • 举报
回复
我自己已经得到答案,信号量放错了地方,应该放在点击OK的响应下

29,028

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧