开发者

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

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 th开发者_运维知识库e process to finish using:

[task waitUntilExit];

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


-[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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜