0

I need some UIViewControllers that receive a NSNotification from the app delegate. It's like a timer, but every UIViewController handle your way. My problem is: when I interact with user interface, the UIViewController doesn't receive the notification, causing problems.

Here is my code in AppDelegate:

-(void)updateCounter:(NSTimer *)theTimer{
    [[NSNotificationCenter defaultCenter] postNotificationName:TimeTickNotification object:nil];
}

//*called by some trigger in the app
-(void) startTimer{
    timer = [NSTimer
             scheduledTimerWithTimeInterval:0.5
             target:self
             selector:@selector(updateCounter:)
             userInfo:nil
             repeats:YES];
}

I am handling the notifications in each UIViewController like this:

-(void) updateGlobalTime:(NSNotification *) notification{
        totalTime = [NSNumber numberWithFloat:([ficha.tempoTotal floatValue] + STEP)];
}




-(void) viewWillAppear:(BOOL)animated {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateGlobalTime:)
                                                 name:TimeTickNotification
                                               object:nil];


}

What should I do to interact with UI and update it at same time? Maybe the NSNotification is not being thrown while user interacts with UI.

marceloquinta
  • 713
  • 12
  • 20

2 Answers2

1

You need to make sure you're updating any UI on the main thread. If you want to update the UI to have the new totalTime in a label or something, make sure the setText: function is running on the main thread. You can accomplish that with GCD, like this:

-(void) updateGlobalTime:(NSNotification *) notification{
        totalTime = [NSNumber numberWithFloat:([ficha.tempoTotal floatValue] + STEP)];

        // Update label on main thread
        dispatch_async(dispatch_get_main_queue(), ^{

             [label setText:totalTime];
        });
}
Alexander
  • 565
  • 9
  • 20
  • Alexander, the problem is: the method called from NSNotificationCenter isnt even called when I am scrolling a list inside the UIView. I tried your code and is not working. – marceloquinta Jul 15 '14 at 12:45
1

The solution was to use NSRunLoop, as following:

NSRunLoop *runloop = [NSRunLoop currentRunLoop];
timer = [NSTimer
             scheduledTimerWithTimeInterval:0.5
             target:self
             selector:@selector(updateCounter:)
             userInfo:nil
             repeats:YES];
[runloop addTimer:timer forMode:NSRunLoopCommonModes];
[runloop addTimer:timer forMode:UITrackingRunLoopMode];
marceloquinta
  • 713
  • 12
  • 20