Question

I have a class containing a method with a loop. I need to be able to break the loop if a certain event (e.g. button press) occurs.

I am using the NSNotificationCenter to notify the class containing the loop when the button is pressed.

However, If I press the button while the loop is being executed, the notification occurs after the loop is complete instead of interrupting the loop.

I'm guessing this is because it is operating in the same thread.

So how do I get the NSNotificationCenter operating in a background / different thread? Is this possible? Or is there a better way to do it?

Was it helpful?

Solution

It's not just the notification center.

I have a class containing a method with a loop. I need to be able to break the loop if a certain event (e.g. button press) occurs.

The events for that button press come in on the main thread. If your loop is running on the main thread, then the button press itself does not get processed until your loop is finished. The notification is posted immediately, relative to the button press actually getting processed by your application.

Or, in list form:

  1. The user presses the button.
  2. Your loop runs out of things to do and returns.
  3. The button press arrives in your application and is turned by the button into an action message.
  4. You post the notification.
  5. You receive the notification.

The delay that you're seeing is between steps 1 and 2; step 4 happens immediately after step 3.

Notifications on a local (not distributed) NSNotificationCenter are dispatched on the thread you post them from, so posting it from your action method means that it will be dispatched on the main thread. This is normal and OK.

Move the loop, not the notification, to a background thread, dispatch queue, or operation queue. If you use an operation queue, you may not need the notification at all, as you can tell an operation queue to cancel all pending operations. (Your operations will need to check at any appropriate time(s) whether they have been canceled; for reasons previously discussed, killing a thread/operation at a random time is a Bad Idea.)

Background threads, blocks, and operations can communicate back to the main thread when needed (e.g., to update the UI). To send a message through the main thread's run loop, use performSelectorOnMainThread:withObject:waitUntilDone:. To dispatch a block on the main thread, use dispatch_async and dispatch_get_main_queue. To schedule an operation on the main thread, add it to [NSOperationQueue mainQueue].

For more info, read the Concurrency Programming Guide and the Notification Programming Topics.

OTHER TIPS

I would run your loop in a separate thread, and have an instance variable BOOL abort;, when your button press notification comes in, set abort = TRUE; then in the loop check this value and exit if it is true.

I would run the loop in a separate thread. Even better, make it an NSOperation so that you can call [.. cancel]. Just make sure to use performSelectorOnMainThread when updating the UI from the NSOperation object. It's not a good idea to have a long running loop on the main thread.

You can't put the notification center on another thread. That object is out of your control. The problem isn't so much that they are on the same thread as that you are not allowing the run loop, which is responsible for handling the button press, to do anything. (There's one and only one run loop per thread.) As has been stated by both edsko and Peter Hosey, the button press itself, and in fact your entire UI, is stopped while your loop is running. It is generally a good idea to put long-running operations onto a background thread, then call back to the main thread to update the UI, performSelectorOnMainThread:withObject:waitUntilDone: being an easy way to do such a call back.

That said, if you were to keep the loop on the main thread, you need to let control return to the run loop periodically so that the button press will be registered. There are two ways I can think of to do this. First, you can explicitly give the run loop control briefly during each iteration of your loop:

while( !buttonWasPressed ){

    // Do work...

    // Let the run loop do some processing before the next iteration.
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
}

Or, you can make a single method that consists only of the code from your loop, and use performSelector:withObject:afterDelay: to have the method repeatedly called while still allowing the run loop to work:

- (void) loopTheLoop {

    if( buttonWasPressed ) return;

    // Do work...

    // Run this method again as soon as possible.
    [self performSelector:@selector(loopTheLoop)
               withObject:nil
               afterDelay:0.0];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top