我正在构建一个iOS应用程序,其代码的某些部分依赖于从特定任务返回的成功/失败值。此任务涉及来自库的回调。我希望只有在回调返回成功/失败后才返回此任务的返回值。但是,由于我编写了一个顺序代码,因此即使在回调成功/失败之前,也会返回返回值。
我研究了使用模态视图控制器,根据我的理解,我可以从该视图控制器执行任务,然后返回代码。
但这也不符合我的要求,因为当执行启动回调序列的代码时,我不希望显示新的视图控制器。虽然有一定的回调要求我提示用户提供信息。我在弹出框中执行此操作,并且我考虑在弹出模式中创建视图控制器。但是回调仍然是主线程的一部分,当我的弹出窗口以模态(?)呈现时,我不会收到它们。
根据我目前对这些概念的理解,我不知道如何继续。有没有办法在iOS中做到这一点?
修改 代码执行类似这样的操作
//In CustomTableViewController
-(void) someFunc
{
ENUM_NAME code = [TaskController startTheTask:args];
if(code == SUCCEEDED)
{
//Do Something
}
if(code == FAILED)
{
//Do Something Else
}
}
//In TaskController
-(ENUM_NAME) startTheTask:args
{
startWorkflow(args); //This function registers callback function with the library.
return finalCode; //This is returned even before it is set to SUCCEEDED/FAILED
}
-(void) onCallback:params
{
MSG_TYPE msg = [params getMsg];
if(msg == TASK_FAILED)
finalCode = FAILED;
if(msg == TASK_SUCCEEDED)
finalCode = SUCCEEDED;
if(msg == TASK_SHOW_PROMPT)
{
[PopOverController showPopOver];
}
}
-(void) onUserInfoAdded
{
//This is called when Confirm is clicked in the popover
continueWorkflow(params); //asks for the next callback to happen
}
-(void) onCancleClicked
{
//This is called when Popover is dismissed without entering Info
cancleWorkflow(params); //asks for result of the workflow through callback
}
答案 0 :(得分:1)
您可以使用GCD。例如:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
//put one process here
dispatch_group_leave(group); //when done
});
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
//put another process here
dispatch_group_leave(group); //when done
});
// All updates finished
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// add last steps here after all processess are finished
});
dispatch_release(group);
答案 1 :(得分:-1)
您可以使用信号量来延迟执行,直到块返回:
__block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block NSData *dataFromTheBlock = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// block implementation
// dataFromTheBlock = some data;
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);