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

淺唱寂寞╮ 提交于 2019-12-06 20:37:31

-[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.

even easier:

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