Ignoring user input while waiting for a task - Objective-C

女生的网名这么多〃 提交于 2019-12-08 03:15:36

问题


I have an app with a button 'convert'. When I click this button, the app starts a new process using NSTask and then greys out the button until the process finishes.

My problem is, the app saves any clicks made by the user while it is waiting for the process to finish. So even though the button is grayed out, the user can click it and the process will immediately start again as soon as it finishes.

I'm waiting for the process to finish using:

[task waitUntilExit];

How do I ignore any user input while waiting for this task to finish?


回答1:


-[NSTask waitUntilExit] is, of course, a blocking call. That means the thread pauses (as does the run loop) and all the events that are sent to the thread are queued up until the run loop can process them.

Instead of waitUntilExit, I'd do something like this:

- (IBAction) myButtonMethod {
  NSTask * task = ....;
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskFinished:) name:NSTaskDidTerminateNotification object:task];
  [myButton setEnabled:NO];
  [task launch];
}

- (void) taskFinished:(NSNotification *)note {
  [myButton setEnabled:YES];
}

This will launch your task, disable the button, but not block the thread, because you're not waiting for it to finish. Instead, you're waiting for the asynchronous notification of whenever the task finishes. Since the button is disabled until the task finishes, this will ignore all events sent to it.




回答2:


even easier:

[[UIApplication sharedApplication] beginIgnoringInteractionEvents];


来源:https://stackoverflow.com/questions/1817726/ignoring-user-input-while-waiting-for-a-task-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!