0

我需要一些從應用程序代理接收NSNotificationUIViewController。這就像一個計時器,但每個UIViewController處理你的方式。我的問題是:當我與用戶界面交互時,UIViewController未收到通知,導致出現問題。滾動內部UITableView時處理NSNotification

這是我在的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]; 
} 

我處理每個UIViewController這樣的通知:

-(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]; 


} 

我應該怎麼做與UI交互,並在同一時間更新?也許NSNotification不會在用戶與UI交互時拋出。

+0

你在主線程可以發佈您的通知? – RaffAl

+0

@reecon是的,它在主線程中。這樣對嗎?! – marceloquinta

回答

1

的解決方案是使用NSRunLoop,如下:

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]; 
1

您需要確保您正在更新主線程上的任何UI。如果您想要更新UI以在標籤中添加新的totalTime,請確保setText:函數正在主線程上運行。你可以做到與GCD,像這樣:

-(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]; 
     }); 
} 
+0

亞歷山大,問題是:當我在UIView中滾動列表時,調用NSNotificationCenter的方法甚至沒有調用。我試過你的代碼,並沒有工作。 – marceloquinta