iPhone注册时钟更新

Mec*_*eer 5 iphone objective-c clock nstimer

我的应用程序中的视图有一个时钟,我想与系统保持同步.许多Stack问题以NSTimer为中心,但在此之前,我想检查是否有可以注册的系统通知,每分钟都会触发一次.

这样的事情存在吗?我正在通过NSNotificationCenter查看,但到目前为止还没有任何内容.

beg*_*ggs 9

您可以通过计算分钟的下一个更改来使用NSTimer's initWithFireDate来点击分钟:

NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"ss"];
int currentTimeSeconds = [dateFormatter stringFromDate:currentDate].intValue;

NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:60 - currentTimeSeconds];
NSTimer *updateTimer = [[NSTimer alloc] initWithFireDate:fireDate
                                                 interval:60
                                                   target:self
                                                 selector:@selector(updateSelector)
                                                 userInfo:nil
                                                  repeats:YES];

NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:updateTimer forMode:NSDefaultRunLoopMode];
Run Code Online (Sandbox Code Playgroud)


Wri*_*sCS 2

NSNotificationCenter据我所知,不存在这样的电话。这真的就像设置一个NSTimer. 只要您将间隔设置NSTimer1 秒,就应该没问题。以下是我如何在我的一个应用程序的标签中使用时间/日期。

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self 
                 selector:@selector(clockDateAndTime:) userInfo:nil repeats:YES];

-(void)clockDateAndTime:(NSTimer*)timer 
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    NSDate * date = [NSDate date];
    [formatter setDateFormat:@"MMM dd, yyyy hh:mm:ss a"];
    [lblLocalDate setText:[formatter stringFromDate:date]];
}
Run Code Online (Sandbox Code Playgroud)